import { describe, it, expect } from 'vitest'
import { readFileSync } from 'node:fs'
import { resolve } from 'node:path'
import { checkSortTokens } from '../scripts/audit-sort-tokens.mjs'

describe('checkSortTokens', () => {
  it('真实 variables.css 通过（0 violation）', () => {
    const css = readFileSync(resolve(__dirname, '../src/tokens/variables.css'), 'utf8')
    const r = checkSortTokens(css)
    expect(r.violations).toEqual([])
    expect(r.ok).toBe(true)
  })

  it('I1：同块内重复分组标题 → duplicate-label', () => {
    const css = [
      ':root {',
      '  /* ===== Icon ===== */',
      '  --icon-a: #111;',
      '  /* ===== Icon ===== */',
      '  --icon-b: #222;',
      '}',
    ].join('\n')
    const r = checkSortTokens(css)
    expect(r.ok).toBe(false)
    expect(r.violations.some(v => v.type === 'duplicate-label')).toBe(true)
  })

  it('I2：块顶标签前的裸 token → orphan-token', () => {
    const css = [
      ':root {',
      '  --orphan: #111;',
      '  /* ===== Icon ===== */',
      '  --icon-a: #222;',
      '}',
    ].join('\n')
    const r = checkSortTokens(css)
    expect(r.ok).toBe(false)
    expect(r.violations.some(v => v.type === 'orphan-token')).toBe(true)
  })

  it('零误报：Domain 式同前缀故意分两处（标题文字不同）通过', () => {
    const css = [
      ':root {',
      '  /* Notification variant bg */',
      '  --notification-bg-dark: #111;',
      '  /* Notification */',
      '  --notification-width: 480px;',
      '}',
    ].join('\n')
    const r = checkSortTokens(css)
    expect(r.ok).toBe(true)
  })

  it('零误报：标签写在 :root { 之外（Spacing 式）通过', () => {
    const css = [
      '/* ── Spacing ── */',
      ':root {',
      '  --sp-xxs: 4px;',
      '  --sp-xs: 8px;',
      '}',
    ].join('\n')
    const r = checkSortTokens(css)
    expect(r.ok).toBe(true)
  })

  it('零误报：块标签与 :root 之间隔着 @font-face（Typography 式）通过', () => {
    const css = [
      '/* ── Typography ── */',
      '@font-face {',
      "  font-family: 'X';",
      '}',
      ':root {',
      '  --font-family-en: sans-serif;',
      '}',
    ].join('\n')
    const r = checkSortTokens(css)
    expect(r.ok).toBe(true)
  })
})
