const fs = require('fs');
const path = require('path');
const yaml = require('js-yaml');

const PROVIDERS = {
  ddev: {
    configPath: path.join('.ddev', 'config.yaml')
  },
  lando: {
    configPath: '.lando.yml'
  },
  dockerCompose: {
    configPaths: ['compose.yaml', 'docker-compose.yml']
  }
};

function findProjectRoot(startDir = process.cwd()) {
  let current = path.resolve(startDir);

  while (true) {
    if (fs.existsSync(path.join(current, PROVIDERS.ddev.configPath))) {
      return { provider: 'ddev', path: current };
    }

    if (fs.existsSync(path.join(current, PROVIDERS.lando.configPath))) {
      return { provider: 'lando', path: current };
    }

    if (PROVIDERS.dockerCompose.configPaths.some(configPath => fs.existsSync(path.join(current, configPath)))) {
      return { provider: 'docker-compose', path: current };
    }

    const parent = path.dirname(current);
    if (parent === current) return null;
    current = parent;
  }
}

function buildProjectId(provider, projectPath) {
  return `${provider}:${path.resolve(projectPath)}`;
}

function readProjectConfig(provider, projectPath) {
  if (provider === 'ddev') {
    const configPath = path.join(projectPath, PROVIDERS.ddev.configPath);
    const config = yaml.load(fs.readFileSync(configPath, 'utf8')) || {};
    return {
      name: config.name || path.basename(projectPath),
      preferredUrl: config.name ? `https://${config.name}.ddev.site` : undefined,
      raw: config
    };
  }

  if (provider === 'lando') {
    const configPath = path.join(projectPath, PROVIDERS.lando.configPath);
    const config = yaml.load(fs.readFileSync(configPath, 'utf8')) || {};
    return {
      name: config.name || path.basename(projectPath),
      raw: config
    };
  }

  return {
    name: path.basename(projectPath),
    raw: {}
  };
}

function detectProject(startDir = process.cwd()) {
  const root = findProjectRoot(startDir);
  if (!root) return null;

  const config = readProjectConfig(root.provider, root.path);

  return {
    id: buildProjectId(root.provider, root.path),
    name: config.name,
    path: root.path,
    provider: root.provider,
    exposeEnabled: false,
    preferredUrl: config.preferredUrl
  };
}

module.exports = {
  buildProjectId,
  detectProject,
  findProjectRoot,
  readProjectConfig
};
