import { existsSync, readFileSync } from 'node:fs'
import path from 'node:path'

const root = process.cwd()
const appJsonPath = path.join(root, 'dist', 'app.json')
const pageMetaPath = path.join(root, 'dist', 'page-meta.json')
const skillRoot = path.join(root, 'dist', 'skills', 'service-assistant')

function fail(message) {
  console.error(`[verify-ai-config] ${message}`)
  process.exit(1)
}

function readJson(filePath) {
  if (!existsSync(filePath)) fail(`missing ${path.relative(root, filePath)}`)
  return JSON.parse(readFileSync(filePath, 'utf8'))
}

const app = readJson(appJsonPath)
if (!app.agent?.skills?.some((skill) => skill.name === 'dlbdi-service' && skill.path === 'skills/service-assistant')) {
  fail('dist/app.json missing agent.skills dlbdi-service')
}
if (app.agent?.pageMetadata !== 'page-meta.json') fail('dist/app.json agent.pageMetadata must be page-meta.json')

for (const fileName of ['SKILL.md', 'mcp.json', 'index.js']) {
  if (!existsSync(path.join(skillRoot, fileName))) fail(`missing dist/skills/service-assistant/${fileName}`)
}

const pageMeta = readJson(pageMetaPath)
const pages = Array.isArray(pageMeta.pages) ? pageMeta.pages : []
const forbidden = /(auth\/|staff\/|checkin\/|checkout|cart|account\/settings|account\/ai-settings|expert-home|pc-confirm)/
const leaked = pages.map((page) => page.path || '').filter((page) => forbidden.test(page))
if (leaked.length) fail(`page-meta includes forbidden pages: ${leaked.join(', ')}`)

console.log(`[verify-ai-config] ok: ${app.agent.skills.length} skill(s), ${pages.length} page metadata entries`)
