import type { ProjectInfo, McmInfo } from './types.js';

/**
 * Scans the static/projectes/ directory structure to discover available projects and MCMs.
 *
 * Expected structure:
 *   projectes/{PROJECT}/excel/{PROJECT}_SYSDL_{MCM}*.xlsx
 *   projectes/{PROJECT}/pdf/{PROJECT}_SYSDL_{MCM}*-SYSDL.pdf
 *
 * Since we're in a static SPA, we use a manifest approach:
 * At build time or at runtime, we fetch a directory listing.
 * For simplicity, we'll use a manifest file that can be auto-generated.
 */

// We'll scan using a known project list fetched from a manifest
// For the static SPA, we generate a manifest at build time via a vite plugin,
// or we hardcode discovery by trying known paths.

const MCM_REGEX = /SYSDL[_ ]+(MCM\d+)/i;

export async function discoverProjects(): Promise<ProjectInfo[]> {
  try {
    const resp = await fetch('/projectes/manifest.json');
    if (resp.ok) {
      return await resp.json();
    }
  } catch {
    // manifest doesn't exist, fall through
  }

  // Fallback: try to discover from known project names
  // This won't work in pure static hosting without a manifest
  // So we provide a way to scan from the file input
  return [];
}

export function parseProjectFiles(files: FileList): ProjectInfo[] {
  const projectMap = new Map<string, Map<string, { excel: string; pdf: string | null }>>();

  for (const file of files) {
    const parts = file.webkitRelativePath?.split('/') || file.name.split('/');
    if (parts.length < 4) continue;

    const projectName = parts[1] || parts[0];
    const folder = parts[2]; // 'excel' or 'pdf'
    const fileName = parts[parts.length - 1];

    if (!projectMap.has(projectName)) {
      projectMap.set(projectName, new Map());
    }

    const mcmMatch = fileName.match(MCM_REGEX);
    if (!mcmMatch) continue;
    const mcmName = mcmMatch[1];

    const mcms = projectMap.get(projectName)!;
    if (!mcms.has(mcmName)) {
      mcms.set(mcmName, { excel: '', pdf: null });
    }

    if (folder === 'excel' && fileName.endsWith('.xlsx')) {
      mcms.get(mcmName)!.excel = file.webkitRelativePath || file.name;
    } else if (folder === 'pdf' && fileName.endsWith('.pdf')) {
      mcms.get(mcmName)!.pdf = file.webkitRelativePath || file.name;
    }
  }

  const projects: ProjectInfo[] = [];
  for (const [name, mcms] of projectMap) {
    const mcmList: McmInfo[] = [];
    for (const [mcmName, paths] of mcms) {
      mcmList.push({
        name: mcmName,
        excelPath: paths.excel,
        pdfPath: paths.pdf,
      });
    }
    mcmList.sort((a, b) => a.name.localeCompare(b.name));
    projects.push({ name, mcms: mcmList });
  }
  projects.sort((a, b) => a.name.localeCompare(b.name));
  return projects;
}
