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 execMigrationOnce(db, file) {
  try {
    db.exec(fs.readFileSync(path.join(workerRoot, file), 'utf8'))
  } catch (error) {
    if (!/duplicate column|already exists/i.test(error?.message || '')) throw error
  }
}

test('text-only create, evaluate and run results become durable artifacts', async (t) => {
  const tempRoot = fs.mkdtempSync(path.join(os.tmpdir(), 'aipros-mode-artifacts-'))
  process.env.DB_PATH = path.join(tempRoot, 'test.db')
  process.env.OUTPUTS_DIR = path.join(tempRoot, 'outputs')
  t.after(() => fs.rmSync(tempRoot, { recursive: true, force: true }))

  const { default: app } = await import('../index.js')
  const { rawDB } = await import('../db.js')
  execMigrationOnce(rawDB, 'migrations/0010_runtime_engines.sql')
  execMigrationOnce(rawDB, 'migrations/0014_local_runtime_agents.sql')

  rawDB.prepare('UPDATE runtime_engines SET enabled = 0, is_active = 0').run()
  rawDB.prepare(`
    UPDATE runtime_engines
    SET local_command = ?, local_args_json = ?, enabled = 1, is_active = 1,
        purpose_scopes_json = '["create","evaluate","run"]'
    WHERE code = 'local-workbuddy'
  `).run(process.execPath, JSON.stringify(['-e', "process.stdout.write('runtime text result')"]))
  rawDB.prepare(`
    UPDATE runtime_agents
    SET runtime_code = 'local-workbuddy', applies_to_json = '["create","evaluate","run"]', enabled = 1
    WHERE id IN ('agent-skill-creator','agent-skill-evaluator','agent-skill-runner')
  `).run()

  const expected = {
    create: 'CREATE_RESULT.md',
    evaluate: 'EVALUATION_REPORT.md',
    run: 'RUN_RESULT.md',
  }
  const headers = { 'Content-Type': 'application/json', 'X-User-Email': '494161546@qq.com' }

  for (const mode of Object.keys(expected)) {
    const response = await app.request('/api/skill-run/stream', {
      method: 'POST', headers,
      body: JSON.stringify({
        mode,
        systemPrompt: mode === 'run' ? '# runner' : undefined,
        messages: [{ role: 'user', content: `${mode} test` }],
      }),
    })
    assert.equal(response.status, 200)
    const text = await response.text()
    const sessionId = text.match(/"sessionId":"([^"]+)"/)?.[1]
    assert.ok(sessionId)
    assert.match(text, new RegExp(`"t":"artifact"[\\s\\S]*${expected[mode]}`))
    assert.match(text, new RegExp(`"t":"files"[\\s\\S]*${expected[mode]}`))

    const artifact = await app.request(
      `/api/skill-run/outputs/${encodeURIComponent(sessionId)}/${encodeURIComponent(expected[mode])}`,
      { headers: { 'X-User-Email': '494161546@qq.com' } },
    )
    assert.equal(artifact.status, 200)
    assert.match(await artifact.text(), /runtime text result/)
  }
})
