import { readFile } from 'node:fs/promises';

export interface MarkerResult {
  isGenerated: boolean;
  source: string | null;
  target: string | null;
}

const MARKER_PATTERNS = [
  '<!-- PromptScript',
  '# promptscript-generated:',
  '> Auto-generated by PromptScript',
];

const SOURCE_TARGET_RE = /\|\s*source:\s*(\S+)\s*\|\s*target:\s*(\S+)/;

export async function detectMarker(filePath: string): Promise<MarkerResult> {
  let content: string;
  try {
    content = await readFile(filePath, 'utf-8');
  } catch {
    return { isGenerated: false, source: null, target: null };
  }

  const lines = content.split('\n').slice(0, 50);
  for (const line of lines) {
    if (MARKER_PATTERNS.some((pattern) => line.includes(pattern))) {
      const match = SOURCE_TARGET_RE.exec(line);
      return {
        isGenerated: true,
        source: match?.[1] ?? null,
        target: match?.[2] ?? null,
      };
    }
  }

  return { isGenerated: false, source: null, target: null };
}
