import { Hono } from 'hono'
import { DB } from '../db.js'
import fs from 'fs'
import path from 'path'

const app = new Hono()

const ADMIN_EMAIL = '494161546@qq.com'
const ADMIN_PHONE = '13136092523'

export const SYSTEM_SKILL_SLOTS = [
  {
    kind: 'creator',
    label: 'Skill 创建器',
    defaultName: 'Skill Creator',
    defaultDescription: 'AI 创建请求直连配置运行时时使用的可选系统 Skill',
  },
  {
    kind: 'evaluator',
    label: 'Skill 评测器',
    defaultName: 'Skill Evaluator',
    defaultDescription: '平台评测 Skill 包质量、输出整改清单时使用的系统 Skill',
  },
]

const VALID_KINDS = new Set(SYSTEM_SKILL_SLOTS.map(slot => slot.kind))
const DEFAULT_SYSTEM_SKILL_FOLDERS = {
  creator: 'skill-creator',
  evaluator: 'skill-evaluator',
}

function isAdmin(c) {
  const id = c.get('identity') || {}
  return id.email === ADMIN_EMAIL || id.phone === ADMIN_PHONE
}

function normalizeKind(kind) {
  const value = String(kind || '').trim().toLowerCase()
  return VALID_KINDS.has(value) ? value : ''
}

function slotFor(kind) {
  return SYSTEM_SKILL_SLOTS.find(slot => slot.kind === kind)
}

function defaultSystemSkillRoot() {
  return process.env.SYSTEM_SKILL_ROOT || '/Users/Administrator/.codex/skills'
}

function defaultSystemSkillPath(kind) {
  const folder = DEFAULT_SYSTEM_SKILL_FOLDERS[kind]
  if (!folder) return ''
  return path.join(defaultSystemSkillRoot(), folder, 'SKILL.md')
}

export async function ensureSystemSkillsTable() {
  await DB.prepare(`
    CREATE TABLE IF NOT EXISTS system_skills (
      kind        TEXT PRIMARY KEY,
      name        TEXT,
      description TEXT,
      content     TEXT NOT NULL DEFAULT '',
      source_name TEXT,
      enabled     INTEGER NOT NULL DEFAULT 1,
      created_at  INTEGER NOT NULL DEFAULT (unixepoch()),
      updated_at  INTEGER NOT NULL DEFAULT (unixepoch()),
      CHECK (kind IN ('creator', 'evaluator'))
    )
  `).run()
}

function toApiSkill(kind, row) {
  const slot = slotFor(kind)
  return {
    kind,
    label: slot.label,
    name: row?.name || slot.defaultName,
    description: row?.description || slot.defaultDescription,
    content: row?.content || '',
    sourceName: row?.source_name || '',
    enabled: !!(row && Number(row.enabled) === 1 && String(row.content || '').trim()),
    createdAt: row?.created_at || null,
    updatedAt: row?.updated_at || null,
  }
}

async function loadRow(kind) {
  await ensureSystemSkillsTable()
  return DB.prepare(`
    SELECT kind, name, description, content, source_name, enabled, created_at, updated_at
    FROM system_skills
    WHERE kind = ?
  `).bind(kind).first()
}

export async function getActiveSystemSkillContent(kind) {
  const normalized = normalizeKind(kind)
  if (!normalized) return ''
  const row = await loadRow(normalized)
  if (!row || Number(row.enabled) !== 1) return ''
  return String(row.content || '').trim()
}

app.get('/', async (c) => {
  if (!isAdmin(c)) return c.json({ error: '无权限' }, 403)
  await ensureSystemSkillsTable()
  const rows = await DB.prepare(`
    SELECT kind, name, description, content, source_name, enabled, created_at, updated_at
    FROM system_skills
  `).all()
  const byKind = new Map((rows.results || []).map(row => [row.kind, row]))
  return c.json({
    slots: SYSTEM_SKILL_SLOTS.map(slot => toApiSkill(slot.kind, byKind.get(slot.kind))),
  })
})

app.get('/:kind', async (c) => {
  if (!isAdmin(c)) return c.json({ error: '无权限' }, 403)
  const kind = normalizeKind(c.req.param('kind'))
  if (!kind) return c.json({ error: '未知系统 Skill 类型' }, 404)
  const row = await loadRow(kind)
  return c.json({ skill: toApiSkill(kind, row) })
})

app.put('/:kind', async (c) => {
  if (!isAdmin(c)) return c.json({ error: '无权限' }, 403)
  const kind = normalizeKind(c.req.param('kind'))
  if (!kind) return c.json({ error: '未知系统 Skill 类型' }, 404)

  let body = {}
  try { body = await c.req.json() } catch {}
  const content = String(body.content || '').trim()
  if (!content) return c.json({ error: '系统 Skill 内容不能为空' }, 400)

  const slot = slotFor(kind)
  const name = String(body.name || slot.defaultName).trim().slice(0, 120)
  const description = String(body.description || slot.defaultDescription).trim().slice(0, 500)
  const sourceName = String(body.sourceName || body.source_name || '').trim().slice(0, 240)
  const enabled = body.enabled === false ? 0 : 1

  await ensureSystemSkillsTable()
  await DB.prepare(`
    INSERT INTO system_skills (kind, name, description, content, source_name, enabled, created_at, updated_at)
    VALUES (?, ?, ?, ?, ?, ?, unixepoch(), unixepoch())
    ON CONFLICT(kind) DO UPDATE SET
      name = excluded.name,
      description = excluded.description,
      content = excluded.content,
      source_name = excluded.source_name,
      enabled = excluded.enabled,
      updated_at = unixepoch()
  `).bind(kind, name, description, content, sourceName, enabled).run()

  const row = await loadRow(kind)
  return c.json({ ok: true, skill: toApiSkill(kind, row) })
})

app.post('/:kind/import-default', async (c) => {
  if (!isAdmin(c)) return c.json({ error: '无权限' }, 403)
  const kind = normalizeKind(c.req.param('kind'))
  if (!kind) return c.json({ error: '未知系统 Skill 类型' }, 404)

  const filePath = defaultSystemSkillPath(kind)
  let content = ''
  try {
    content = await fs.promises.readFile(filePath, 'utf8')
  } catch {
    return c.json({ error: `未找到本机默认系统 Skill：${filePath}` }, 404)
  }
  if (!content.trim()) return c.json({ error: `本机默认系统 Skill 内容为空：${filePath}` }, 400)

  const slot = slotFor(kind)
  const folder = DEFAULT_SYSTEM_SKILL_FOLDERS[kind]
  await ensureSystemSkillsTable()
  await DB.prepare(`
    INSERT INTO system_skills (kind, name, description, content, source_name, enabled, created_at, updated_at)
    VALUES (?, ?, ?, ?, ?, 1, unixepoch(), unixepoch())
    ON CONFLICT(kind) DO UPDATE SET
      name = excluded.name,
      description = excluded.description,
      content = excluded.content,
      source_name = excluded.source_name,
      enabled = 1,
      updated_at = unixepoch()
  `).bind(
    kind,
    slot.defaultName,
    slot.defaultDescription,
    content.trim(),
    `本机默认 ${folder}/SKILL.md`
  ).run()

  const row = await loadRow(kind)
  return c.json({ ok: true, skill: toApiSkill(kind, row) })
})

app.delete('/:kind', async (c) => {
  if (!isAdmin(c)) return c.json({ error: '无权限' }, 403)
  const kind = normalizeKind(c.req.param('kind'))
  if (!kind) return c.json({ error: '未知系统 Skill 类型' }, 404)
  await ensureSystemSkillsTable()
  await DB.prepare(`
    INSERT INTO system_skills (kind, name, description, content, source_name, enabled, created_at, updated_at)
    VALUES (?, ?, ?, '', '', 0, unixepoch(), unixepoch())
    ON CONFLICT(kind) DO UPDATE SET
      content = '',
      source_name = '',
      enabled = 0,
      updated_at = unixepoch()
  `).bind(kind, slotFor(kind).defaultName, slotFor(kind).defaultDescription).run()
  const row = await loadRow(kind)
  return c.json({ ok: true, skill: toApiSkill(kind, row) })
})

export default app
