import fs from 'node:fs';
import path from 'node:path';
import { env } from '../config/env.js';

function normalizeCandidatePath(value: string | null | undefined) {
  const normalized = String(value ?? '').trim();
  return normalized ? path.resolve(normalized) : null;
}

function getCandidateScore(candidatePath: string) {
  let score = 0;

  if (fs.existsSync(path.join(candidatePath, 'AGENTS.md'))) {
    score += 4;
  }

  if (fs.existsSync(path.join(candidatePath, 'package.json'))) {
    score += 2;
  }

  if (fs.existsSync(path.join(candidatePath, 'etc', 'servers', 'work-server'))) {
    score += 1;
  }

  return score;
}

export function resolveMainProjectRoot() {
  const candidates = [
    env.SERVER_COMMAND_MAIN_PROJECT_ROOT,
    env.PLAN_MAIN_PROJECT_REPO_PATH,
    env.PLAN_GIT_REPO_PATH,
    env.SERVER_COMMAND_PROJECT_ROOT,
    path.resolve(process.cwd(), '../../..'),
    process.cwd(),
    '/workspace/main-project',
  ]
    .map((value) => normalizeCandidatePath(value))
    .filter((value, index, array): value is string => Boolean(value) && array.indexOf(value) === index);

  const existingCandidates = candidates.filter((candidate) => {
    try {
      return fs.statSync(candidate).isDirectory();
    } catch {
      return false;
    }
  });

  if (existingCandidates.length === 0) {
    return candidates[0] ?? path.resolve(process.cwd(), '../../..');
  }

  return existingCandidates
    .slice()
    .sort((left, right) => getCandidateScore(right) - getCandidateScore(left))[0];
}
