import assert from 'node:assert/strict'
import fs from 'node:fs'
import os from 'node:os'
import path from 'node:path'
import test from 'node:test'
import { fileURLToPath } from 'node:url'

const __dirname = path.dirname(fileURLToPath(import.meta.url))
const workerRoot = path.resolve(__dirname, '../..')

function execMigration(rawDB, file) {
  rawDB.exec(fs.readFileSync(path.join(workerRoot, 'migrations', file), 'utf8'))
}

test('ops rankings aggregate domains and hot skills from real skill activity', async (t) => {
  const tempRoot = fs.mkdtempSync(path.join(os.tmpdir(), 'aipros-ops-rankings-'))
  process.env.DB_PATH = path.join(tempRoot, 'test.db')
  t.after(() => fs.rmSync(tempRoot, { recursive: true, force: true }))

  const { default: app } = await import('../index.js')
  const { rawDB } = await import('../db.js')

  execMigration(rawDB, '0001_init.sql')
  execMigration(rawDB, '0002_skill_stats.sql')
  execMigration(rawDB, '0004_skill_api.sql')
  execMigration(rawDB, '0007_skill_visibility.sql')

  rawDB.prepare(
    `INSERT INTO categories (id, parent_id, code, name, level, path, status, sort)
     VALUES (?, NULL, ?, ?, 1, ?, 'active', 1)`
  ).run('sales', '1.0', '销售域', '销售域')
  rawDB.prepare(
    `INSERT INTO categories (id, parent_id, code, name, level, path, status, sort)
     VALUES (?, NULL, ?, ?, 1, ?, 'active', 2)`
  ).run('finance', '2.0', '财务域', '财务域')

  rawDB.prepare(
    `INSERT INTO skills
     (id, name, description, node_id, node_path, source, status, creator_name, creator_email,
      package_key, visibility, download_count, like_count, dislike_count)
     VALUES (?, ?, ?, ?, ?, 'upload', ?, 'Owner', 'owner@example.com', ?, 'public', ?, ?, ?)`
  ).run('skill_sales_hot', '销售线索评分', '销售域高频 Skill', 'sales', '销售域 / 线索管理', 'published', 'pkg/sales.zip', 8, 5, 1)
  rawDB.prepare(
    `INSERT INTO skills
     (id, name, description, node_id, node_path, source, status, creator_name, creator_email,
      package_key, visibility, download_count, like_count, dislike_count)
     VALUES (?, ?, ?, ?, ?, 'upload', ?, 'Owner', 'owner@example.com', ?, 'public', ?, ?, ?)`
  ).run('skill_finance', '报销审查', '财务域 Skill', 'finance', '财务域 / 费用报销', 'published', 'pkg/finance.zip', 2, 1, 0)

  rawDB.prepare(
    `INSERT INTO api_keys (id, skill_id, name, key_hash, key_prefix, created_by_email)
     VALUES (?, ?, ?, ?, ?, ?)`
  ).run('key_sales', 'skill_sales_hot', 'sales-key', 'hash-sales', 'sk_live_sale...', 'owner@example.com')

  for (const row of [
    ['skill_sales_hot', '销售线索评分', 'key_sales', 'success', 120],
    ['skill_sales_hot', '销售线索评分', 'key_sales', 'success', 180],
    ['skill_sales_hot', '销售线索评分', 'key_sales', 'error', 260],
  ]) {
    rawDB.prepare(
      `INSERT INTO skill_invocations
       (skill_id, skill_name, api_key_id, caller_ip, request_input, response_output, response_status, latency_ms)
       VALUES (?, ?, ?, '127.0.0.1', '{}', '{}', ?, ?)`
    ).run(...row)
  }

  const res = await app.request('/api/ops/rankings', {
    headers: { 'X-User-Email': 'operator@example.com' },
  })
  assert.equal(res.status, 200)
  const body = await res.json()

  assert.equal(body.summary.totalSkills, 2)
  assert.equal(body.summary.publishedSkills, 2)
  assert.equal(body.summary.apiCalls, 3)
  assert.equal(body.domains[0].domain, '销售域')
  assert.equal(body.domains[0].apiCalls, 3)
  assert.equal(body.domains[0].downloads, 8)
  assert.equal(body.topSkills[0].id, 'skill_sales_hot')
  assert.ok(body.topSkills[0].hotScore > body.topSkills[1].hotScore)
})
