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

const ROOT = path.resolve(path.dirname(fileURLToPath(import.meta.url)), '../..')
const PAGE = path.join(ROOT, 'src/pages/CreateSkillChat.jsx')

function pageSource() {
  return fs.readFileSync(PAGE, 'utf8')
}

test('AI creation sends every user request directly to the configured create runtime', () => {
  const source = pageSource()
  assert.match(source, /doSendToAI\(t,\s*\{\s*mode:\s*['"]create['"]\s*\}\)/)
  assert.doesNotMatch(
    source,
    /planSkillCreationAgentTurn|buildSkillCreationClarificationCard|mode:\s*['"]clarify['"]|mode:\s*['"]evaluate['"]/,
  )
})

test('AI creation has no legacy clarification or quality-control UI', () => {
  const source = pageSource()
  const legacyControlPattern = new RegExp([
    'clarification_card',
    'executeEvaluateCard',
    'executeReviseCard',
    'riskAccepted',
    ['Harness', 'CheckBox'].join(''),
    ['generation', 'Harness'].join(''),
    ['har', 'ness'].join(''),
  ].join('|'), 'i')
  assert.doesNotMatch(source, legacyControlPattern)
  assert.doesNotMatch(source, /输出形式|边界规则|确认选择并生成|上架前评测|评测修改/)
})

test('runtime result stays conversational and exposes one explicit one-click publish action', () => {
  const source = pageSource()
  assert.match(source, /setLatestPublishResult\(\{[\s\S]*?text:\s*finalAssistantText[\s\S]*?entries:\s*generatedEntries/)
  assert.match(source, /handlePublishLatestResult/)
  assert.doesNotMatch(source, /\n\s+appendPublishCard\(\{\n\s+text:\s*finalAssistantText/)
  assert.match(source, /一键创建并立即发布 Skill/)
  assert.match(source, /const saved = await createSkillApi\(/)
  assert.match(source, /await updateSkillApi\(saved\.id,\s*\{\s*status:\s*['"]published['"]\s*\}\)/)
})

test('publish uses generated files when present and falls back to runtime text', () => {
  const source = pageSource()
  assert.match(source, /generatedEntries\.length\s*>\s*0/)
  assert.match(source, /runtimeText/)
  assert.match(source, /source:\s*entries\.length\s*\?\s*['"]upload['"]\s*:\s*['"]create['"]/)
})

test('missing node is requested only when the user confirms publication', () => {
  const source = pageSource()
  assert.match(source, /if \(!nodeId\)\s*\{[\s\S]*?setPendingPublishCardId\(card\.id\)[\s\S]*?setShowNodePicker\(true\)/)
  assert.doesNotMatch(source, /ensureNode\(['"](?:send|create|generate)['"]\)/)
})
