/**
 * Content type detection for section-split stage.
 *
 * Detects whether content is JSON, YAML, XML, code, or prose.
 * This determines how section-split breaks the content apart:
 * - JSON/YAML/XML → structural splitting (keys, elements)
 * - Code → function/class boundaries
 * - Prose → markdown headers or blank-line paragraphs
 */

export type DetectedContentType = 'json' | 'yaml' | 'xml' | 'code' | 'prose';

/**
 * Detect the content type of a string.
 * Uses structural heuristics — no parsing required for detection.
 */
export function detectContentType(content: string): DetectedContentType {
  const trimmed = content.trimStart();
  if (!trimmed) return 'prose';

  // JSON: starts with { or [
  if (trimmed[0] === '{' || trimmed[0] === '[') {
    // Verify it's actually parseable JSON (not just prose starting with {)
    try {
      JSON.parse(trimmed);
      return 'json';
    } catch {
      // Could be a code block starting with { — check further
      if (trimmed[0] === '{') return 'code';
    }
  }

  // XML: starts with <? or < followed by a tag name
  if (trimmed.startsWith('<?xml')) return 'xml';
  if (trimmed[0] === '<' && /^<[a-zA-Z]/.test(trimmed)) {
    // Check if it looks like XML/HTML (has closing tags) vs just a < comparison
    if (/<\/[a-zA-Z]/.test(trimmed)) return 'xml';
  }

  // YAML: top-level key: value pattern on first line (not inside prose)
  // Must have multiple key: value lines to distinguish from prose with colons
  const lines = trimmed.split('\n').slice(0, 10);
  const yamlKeyLines = lines.filter((l) => /^[a-zA-Z_][a-zA-Z0-9_-]*:\s/.test(l));
  if (yamlKeyLines.length >= 2) return 'yaml';

  // Code: starts with common code patterns
  if (/^(function |class |def |const |let |var |import |export |package |module |#include |#!\/)/.test(trimmed)) {
    return 'code';
  }

  // Code: high density of code-like patterns
  const codeIndicators = [
    /^(if|for|while|switch|return|try|catch)\s*[({]/m,
    /=>/,
    /\.\w+\(/,
    /;\s*$/m,
  ];
  const codeScore = codeIndicators.filter((re) => re.test(trimmed)).length;
  if (codeScore >= 3) return 'code';

  return 'prose';
}
