import { readFile } from 'fs/promises';
import { basename } from 'path';
import { detectFormat, getParser, type DetectedFormat } from './detector.js';
import { mapSections } from './mapper.js';
import { emitPrs } from './emitter.js';
import type { ScoredSection } from './confidence.js';

export interface ImportOptions {
  format?: DetectedFormat;
  dryRun?: boolean;
  outputDir?: string;
}

export interface ImportResult {
  prsContent: string;
  yamlConfig: string;
  sections: ScoredSection[];
  totalConfidence: number;
  warnings: string[];
}

export async function importFile(
  filepath: string,
  options: ImportOptions = {}
): Promise<ImportResult> {
  const raw = await readFile(filepath, 'utf-8');

  if (raw.trim().length === 0) {
    throw new Error('Empty file');
  }

  const format = options.format ?? detectFormat(filepath);
  const parser = getParser(format);
  const markdownSections = parser.parse(raw, filepath);
  const sections = mapSections(markdownSections);

  const totalConfidence =
    sections.length > 0 ? sections.reduce((sum, s) => sum + s.confidence, 0) / sections.length : 0;

  const projectName = deriveProjectName(filepath);
  const prsContent = emitPrs(sections, { projectName });
  const yamlConfig = generateYamlConfig(projectName, format);

  const warnings: string[] = [];
  for (const section of sections) {
    if (section.confidence < 0.5) {
      warnings.push(
        `Low confidence for "${section.heading}" (${Math.round(section.confidence * 100)}%) — review suggested`
      );
    }
  }

  return {
    prsContent,
    yamlConfig,
    sections,
    totalConfidence,
    warnings,
  };
}

function deriveProjectName(filepath: string): string {
  const name = basename(filepath).replace(/\.[^.]+$/, '');
  return name.toLowerCase().replace(/[^a-z0-9-]/g, '-') || 'imported';
}

function generateYamlConfig(projectName: string, format: string): string {
  const lines = [
    `# Generated by prs import`,
    `targets:`,
    `  - name: "${projectName}"`,
    `    format: "${format}"`,
  ];
  return lines.join('\n') + '\n';
}
