import { mkdir, readFile, writeFile } from 'node:fs/promises'
import path from 'node:path'

const sourceRoot = process.argv[2]
const assetPath = process.argv[3]

if (!sourceRoot || !assetPath) {
  throw new Error('usage: node backend/scripts/sync-ai-experts.mjs <agency-agents-zh-dir> <experts-asset.js>')
}

const asset = await readFile(assetPath, 'utf8')
const catalogMatch = asset.match(/^const e=JSON\.parse\(('(?:\\.|[^'])*')\)/s)
if (!catalogMatch) throw new Error('Chinese expert catalog was not found in the supplied asset')

const encodedCatalog = Function(`"use strict"; return ${catalogMatch[1]}`)()
const summaries = JSON.parse(encodedCatalog)
const experts = []

for (const summary of summaries) {
  const promptPath = path.join(sourceRoot, summary.category, `${summary.id}.md`)
  const systemPrompt = await readFile(promptPath, 'utf8')
  experts.push({
    slug: summary.id,
    category: summary.category,
    categoryName: summary.categoryName,
    name: summary.name,
    description: summary.description,
    emoji: summary.emoji,
    color: summary.color,
    systemPrompt,
  })
}

const outputPath = path.resolve('backend/internal/models/experts_catalog.json')
await mkdir(path.dirname(outputPath), { recursive: true })
await writeFile(outputPath, `${JSON.stringify({
  source: 'https://github.com/jnMetaCode/agency-agents-zh',
  reference: 'https://ao.aiolaola.com/experts',
  license: 'MIT',
  experts,
}, null, 2)}\n`, 'utf8')

console.log(`wrote ${experts.length} experts to ${outputPath}`)
