/**
 * Prompt kütüphanesindeki HTML dosyalarından JSON promptları çıkarır
 * ve data/prompt-library/base-prompts.json olarak kaydeder.
 *
 * Kullanım: npx tsx scripts/extract-prompts.ts
 */
import { readdir, readFile, writeFile, mkdir } from 'fs/promises';
import { resolve, dirname } from 'path';
import { fileURLToPath } from 'url';

const __dirname = dirname(fileURLToPath(import.meta.url));
const LIBRARY_DIR = resolve(__dirname, '../../prompt-kutuphanesi');
const OUTPUT_DIR = resolve(__dirname, '../data/prompt-library');

interface ExtractedPrompt {
  id: string;
  sourceFile: string;
  promptIndex: number;
  category: string;
  json: Record<string, unknown>;
}

function decodeHtmlEntities(text: string): string {
  return text
    .replace(/&quot;/g, '"')
    .replace(/&amp;/g, '&')
    .replace(/&lt;/g, '<')
    .replace(/&gt;/g, '>')
    .replace(/&#39;/g, "'")
    .replace(/&apos;/g, "'");
}

function extractJsonBlocks(html: string): string[] {
  const blocks: string[] = [];
  const regex = /<pre\s+class="code-block"\s+id="json-\d+">([\s\S]*?)<\/pre>/g;
  let match: RegExpExecArray | null;
  while ((match = regex.exec(html)) !== null) {
    blocks.push(decodeHtmlEntities(match[1]!.trim()));
  }
  return blocks;
}

function inferCategory(filename: string): string {
  const map: Record<string, string> = {
    'karakter-a.html': 'lifestyle-glamour',
    'karakter-b.html': 'casual-everyday',
    'karakter-c.html': 'fashion-editorial',
    'karakter-d.html': 'intimate-boudoir',
    'karakter-e.html': 'outdoor-adventure',
    'karakter-f.html': 'nightlife-party',
    'karakter-g.html': 'mixed-creative',
  };
  return map[filename] ?? 'uncategorized';
}

async function main() {
  await mkdir(OUTPUT_DIR, { recursive: true });

  const files = (await readdir(LIBRARY_DIR)).filter(
    (f) => f.startsWith('karakter-') && f.endsWith('.html'),
  );

  const allPrompts: ExtractedPrompt[] = [];
  let globalIndex = 0;

  for (const file of files.sort()) {
    const html = await readFile(resolve(LIBRARY_DIR, file), 'utf-8');
    const blocks = extractJsonBlocks(html);
    const category = inferCategory(file);

    console.log(`${file}: ${blocks.length} prompt bulundu (${category})`);

    for (let i = 0; i < blocks.length; i++) {
      try {
        const json = JSON.parse(blocks[i]!);
        globalIndex++;
        allPrompts.push({
          id: `prompt-${String(globalIndex).padStart(4, '0')}`,
          sourceFile: file,
          promptIndex: i + 1,
          category,
          json,
        });
      } catch (err) {
        console.warn(`  ⚠ ${file} prompt #${i + 1}: JSON parse hatası, atlanıyor`);
      }
    }
  }

  const outputPath = resolve(OUTPUT_DIR, 'base-prompts.json');
  await writeFile(outputPath, JSON.stringify(allPrompts, null, 2), 'utf-8');

  console.log(`\n✓ Toplam ${allPrompts.length} prompt çıkarıldı → ${outputPath}`);
}

main().catch(console.error);
