const test = require('node:test')
const assert = require('node:assert')
const {
  extractTemplateIdFromPath,
  parseTopTemplateVersionComment,
  nextTemplateVersionDisplay,
  formatTemplateVersionBannerLine,
  prependTemplateVersionBanner,
  shouldDefaultNoLintLibraryAdd,
  codeAppearsToHaveEditableTemplateFields,
} = require('../src/lib/template-meta')

test('extractTemplateIdFromPath strips .template before extension', () => {
  assert.strictEqual(extractTemplateIdFromPath('/a/HomeHero.template.tsx'), 'HomeHero')
  assert.strictEqual(extractTemplateIdFromPath('/a/hero.jsx'), 'hero')
})

test('parseTopTemplateVersionComment is case-insensitive for template id', () => {
  const code = `// home:v1.0 legacy=false
// @template v2
`
  assert.strictEqual(parseTopTemplateVersionComment(code, 'home'), '1.0')
  assert.strictEqual(parseTopTemplateVersionComment(code, 'HOME'), '1.0')
})

test('nextTemplateVersionDisplay: null -> 1.0, 1.0 -> 2, 2 -> 3', () => {
  assert.strictEqual(nextTemplateVersionDisplay(null), '1.0')
  assert.strictEqual(nextTemplateVersionDisplay('1.0'), '2')
  assert.strictEqual(nextTemplateVersionDisplay('2'), '3')
})

test('prependTemplateVersionBanner inserts before // @template v2', () => {
  const inner = `// @template v2

import x from 'y'
`
  const line = formatTemplateVersionBannerLine('Hero', '2', false)
  const out = prependTemplateVersionBanner(inner, line)
  assert.match(out, /^\/\/ Hero:v2 legacy=false\n\/\/ @template v2\n/)
})

test('prependTemplateVersionBanner prepends when no v2 banner', () => {
  const inner = `import x from 'y'
`
  const line = formatTemplateVersionBannerLine('Hero', '1.0', true)
  const out = prependTemplateVersionBanner(inner, line)
  assert.strictEqual(out, `${line}\n${inner}`)
})

test('shouldDefaultNoLintLibraryAdd requires .template. in basename and version comment', () => {
  const code = `// Widget:v3 legacy=false
export default function W() {}
`
  assert.strictEqual(shouldDefaultNoLintLibraryAdd('/proj/Widget.template.tsx', code), true)
  assert.strictEqual(shouldDefaultNoLintLibraryAdd('/proj/Widget.tsx', code), false)
  assert.strictEqual(shouldDefaultNoLintLibraryAdd('/proj/Widget.template.tsx', 'export default function W() {}'), false)
})

test('codeAppearsToHaveEditableTemplateFields detects $() and @type', () => {
  assert.strictEqual(codeAppearsToHaveEditableTemplateFields('const x = $(a:String="")'), true)
  assert.strictEqual(codeAppearsToHaveEditableTemplateFields('/** @type RichText */'), true)
  assert.strictEqual(codeAppearsToHaveEditableTemplateFields('/** @type {String} */'), true)
  assert.strictEqual(codeAppearsToHaveEditableTemplateFields('export default function X() { return 1 }'), false)
})
