#!/usr/bin/env node
// build-time gate: every clipboard write in `platform/ui/app/` must
// route through the canonical `copyToClipboard` export at
// `hooks/useSelectionMode.ts`. That helper holds the two-path implementation
// (Clipboard API then `document.execCommand('copy')` fallback) that lets the
// admin UI work on plain-HTTP hosts like `realagent-code.local`. A second
// direct call to `navigator.clipboard` would silently re-introduce the
// "Copy failed" regression on those hosts.
//
// Fails if any .ts/.tsx file under `platform/ui/app/` other than
// `hooks/useSelectionMode.ts` calls `navigator.clipboard.writeText`,
// `navigator.clipboard.readText`, or any other clipboard method directly.
// Bare `navigator.clipboard` (feature detection) and comment references are
// allowed — only the operation that bypasses the fallback is the regression.

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

const SCRIPT_DIR = dirname(fileURLToPath(import.meta.url))
const REPO_ROOT = join(SCRIPT_DIR, '..', '..')
const SCAN_ROOT = join(REPO_ROOT, 'platform', 'ui', 'app')
const CANONICAL = join('hooks', 'useSelectionMode.ts')
const PATTERN = /navigator\.clipboard\.\w+\s*\(/

const offenders = []

function walk(dir) {
  for (const entry of readdirSync(dir)) {
    const full = join(dir, entry)
    const stat = statSync(full)
    if (stat.isDirectory()) {
      walk(full)
      continue
    }
    if (!/\.(ts|tsx)$/.test(entry)) continue
    const rel = relative(SCAN_ROOT, full)
    if (rel === CANONICAL) continue
    const text = readFileSync(full, 'utf8')
    const lines = text.split('\n')
    lines.forEach((line, i) => {
      if (PATTERN.test(line)) offenders.push(`${rel}:${i + 1}: ${line.trim()}`)
    })
  }
}

walk(SCAN_ROOT)

if (offenders.length > 0) {
  console.error('check-no-direct-clipboard: found direct navigator.clipboard usage outside hooks/useSelectionMode.ts:')
  for (const o of offenders) console.error('  ' + o)
  console.error('Import { copyToClipboard } from \'./hooks/useSelectionMode\' (or relative equivalent) instead.')
  process.exit(1)
}
