import { readFileSync, readdirSync, statSync } from 'node:fs'
import { join, relative } from 'node:path'

const root = new URL('..', import.meta.url).pathname
const src = join(root, 'src')

const requiredFiles = [
  'src/styles/theme.css',
  'src/styles/components.css',
  'src/styles/element-plus.css'
]

const requiredTokens = [
  '--color-brand: #2b1f99',
  '--color-accent: #3ad4d8',
  '--color-bg:',
  '--color-surface:',
  '--color-border:',
  '--color-text:',
  '--radius-xs: 4px',
  '--radius-sm: 6px',
  '--radius-md: 8px'
]

const bannedEmoji = /[📋📌⚡⏳✅❌🎯🚀💡🔥]/u
const bannedDecor = /(radial-gradient|gradient orb|bokeh|blur\(60px\)|border-radius:\s*(1[2-9]|[2-9]\d)px)/
const migratedMarkers = [
  'clinical-shell',
  'internal-login',
  'period-workbench',
  'period-status-strip',
  'okr-workbench',
  'team-okr-workbench',
  'review-workbench',
  'scoring-worklist',
  'result-workbench',
  'history-workbench',
  'feedback-workbench',
  'org-workbench',
  'log-workbench',
  'dimension-workbench',
  'template-workbench'
]

function walk(dir) {
  return readdirSync(dir).flatMap((name) => {
    const path = join(dir, name)
    return statSync(path).isDirectory() ? walk(path) : [path]
  })
}

const failures = []

for (const file of requiredFiles) {
  try {
    readFileSync(join(root, file), 'utf8')
  } catch {
    failures.push(`missing required style file: ${file}`)
  }
}

const themePath = join(root, 'src/styles/theme.css')
let theme = ''
try {
  theme = readFileSync(themePath, 'utf8')
} catch {}

for (const token of requiredTokens) {
  if (!theme.includes(token)) failures.push(`missing theme token: ${token}`)
}

const main = readFileSync(join(root, 'src/main.js'), 'utf8')
for (const file of requiredFiles) {
  const importPath = './' + file.replace('src/', '')
  if (!main.includes(importPath)) failures.push(`main.js must import ${importPath}`)
}

const layout = readFileSync(join(root, 'src/components/MainLayout.vue'), 'utf8')
const login = readFileSync(join(root, 'src/views/auth/LoginView.vue'), 'utf8')
const periodList = readFileSync(join(root, 'src/views/period/PeriodListView.vue'), 'utf8')
const periodBanner = readFileSync(join(root, 'src/components/PeriodBanner.vue'), 'utf8')
const myOkr = readFileSync(join(root, 'src/views/okr/MyOkrView.vue'), 'utf8')
const teamOkr = readFileSync(join(root, 'src/views/okr/TeamOkrView.vue'), 'utf8')
const scoringEdit = readFileSync(join(root, 'src/views/scoring/ScoringEditView.vue'), 'utf8')
const scoringList = readFileSync(join(root, 'src/views/scoring/ScoringListView.vue'), 'utf8')

if (!layout.includes('clinical-shell')) failures.push('MainLayout must use clinical-shell')
if (!layout.includes('clinical-sidebar')) failures.push('MainLayout must use clinical-sidebar')
if (!login.includes('internal-login')) failures.push('LoginView must use internal-login')
if (login.includes('radial-gradient')) failures.push('LoginView must not use radial-gradient')
if (!periodList.includes('period-workbench')) failures.push('PeriodListView must use period-workbench')
if (!periodList.includes('period-metrics')) failures.push('PeriodListView must show period-metrics')
if (!periodBanner.includes('period-status-strip')) failures.push('PeriodBanner must use period-status-strip')
if (!myOkr.includes('okr-workbench')) failures.push('MyOkrView must use okr-workbench')
if (!myOkr.includes('okr-standard-panel')) failures.push('MyOkrView must use okr-standard-panel')
if (!teamOkr.includes('team-okr-workbench')) failures.push('TeamOkrView must use team-okr-workbench')
if (!scoringEdit.includes('review-workbench')) failures.push('ScoringEditView must use review-workbench')
if (!scoringEdit.includes('evidence-panel')) failures.push('ScoringEditView must use evidence-panel')
if (!scoringEdit.includes('decision-panel')) failures.push('ScoringEditView must use decision-panel')
if (!scoringList.includes('scoring-worklist')) failures.push('ScoringListView must use scoring-worklist')

const requiredClasses = new Map([
  ['src/views/scoring/MyResultView.vue', 'result-workbench'],
  ['src/views/scoring/HistoryView.vue', 'history-workbench'],
  ['src/views/feedback/FeedbackView.vue', 'feedback-workbench'],
  ['src/views/org/OrgView.vue', 'org-workbench'],
  ['src/views/system/LogView.vue', 'log-workbench'],
  ['src/views/system/DimensionConfigView.vue', 'dimension-workbench'],
  ['src/views/period/KpiTemplateView.vue', 'template-workbench']
])

for (const [file, className] of requiredClasses) {
  const text = readFileSync(join(root, file), 'utf8')
  if (!text.includes(className)) failures.push(`${file} must use ${className}`)
}

const vueAndCssFiles = walk(src).filter((file) => /\.(vue|css)$/.test(file))
for (const file of vueAndCssFiles) {
  const text = readFileSync(file, 'utf8')
  const rel = relative(root, file)
  const mustFollowMedtechRules = rel.startsWith('src/styles/') || migratedMarkers.some((marker) => text.includes(marker))
  if (mustFollowMedtechRules && bannedEmoji.test(text)) failures.push(`banned emoji in ${rel}`)
  if (mustFollowMedtechRules && bannedDecor.test(text)) failures.push(`banned decorative style in ${rel}`)
}

if (failures.length) {
  console.error(failures.join('\n'))
  process.exit(1)
}

console.log('medtech theme checks passed')
