import { readFileSync, writeFileSync, statSync, rmSync, existsSync } from 'fs'
import { resolve } from 'path'

/**
 * Remove Clarity's Metropolis @font-face blocks from clr-ui.min.css.
 *
 * Why: Clarity ships Metropolis as base64 data: URLs. The deployed app
 * runs under CSP `default-src 'self'` (no data: font-src), so every page
 * logs a font-load failure for each weight. Firefox preemptively
 * validates every parsed src against CSP even when a later @font-face
 * supersedes the rule at render time, so the only way to silence the
 * console is to remove the offending blocks from the parsed CSS.
 *
 * Our styles.scss declares the same family/weight/style with same-origin
 * .woff files, so removing Clarity's blocks entirely is safe and leaves
 * Metropolis fully functional.
 *
 * Idempotent: matches by font-family, so works on a fresh install or a
 * file that's already been stripped on a previous run.
 */
const target = resolve('node_modules/@clr/ui/clr-ui.min.css')

let css
try {
  css = readFileSync(target, 'utf8')
} catch (err) {
  if (err.code === 'ENOENT') {
    console.log(`skip: ${target} not found (likely pre-install run)`)
    process.exit(0)
  }
  throw err
}

const sizeBefore = statSync(target).size
const blockRe = /@font-face\{[^}]*Metropolis[^}]*\}/g
const matches = css.match(blockRe) ?? []

if (matches.length === 0) {
  console.log(`already stripped: ${target}`)
  process.exit(0)
}

const stripped = css.replace(blockRe, '')
writeFileSync(target, stripped)
const sizeAfter = Buffer.byteLength(stripped)
console.log(
  `removed ${matches.length} Metropolis @font-face block(s) from clr-ui.min.css ` +
    `(${sizeBefore} -> ${sizeAfter} bytes, saved ${sizeBefore - sizeAfter})`
)

// Webpack 5's persistent cache treats node_modules as immutable
// (snapshot.module.managedPaths default), so in-place edits don't
// invalidate cached entries. Drop the Angular build cache so the next
// build re-reads our stripped clr-ui.min.css.
const cacheDir = resolve('.angular/cache')
if (existsSync(cacheDir)) {
  rmSync(cacheDir, { recursive: true, force: true })
  console.log(`cleared ${cacheDir} (webpack persistent cache)`)
}
