/**
 * Pull portal rules out of docs/reference/portal-css.txt verbatim for the bench's
 * browser truth. Pure string work, tested in tests/bench-css.test.ts.
 */

export interface Rule {
  selector: string
  body: string
}

export function parseRules(css: string): Rule[] {
  const rules: Rule[] = []
  const clean = css.replace(/\/\*[\s\S]*?\*\//g, '')
  for (const m of clean.matchAll(/([^{}]+)\{([^{}]*)\}/g)) rules.push({ selector: m[1]!.trim(), body: m[2]!.trim() })
  return rules
}

/** `:hover` / `:active` / `:focus` become classes the harness can set on an element. */
export function rewritePseudo(selector: string): string {
  return selector.replace(/:(hover|active|focus)(?![\w-])/g, '.is-$1')
}

const BOUNDARY = /[\s>+~.:#[,]/

/**
 * True when one comma part of `selector` is `want`, or starts with `want`
 * followed by a pseudo-class, a further compound or a descendant
 * (`.button` matches `.button:hover` and `.button .icon`, not `.button-green`).
 */
export function matches(selector: string, want: string): boolean {
  return selector.split(',').some((raw) => {
    const part = raw.trim()
    if (part === want) return true
    return part.startsWith(want) && BOUNDARY.test(part[want.length]!)
  })
}

/** Every rule matching any of `selectors`, in source order (cascade preserved), pseudo-classes rewritten. */
export function extractRules(css: string, selectors: string[], resolveUrl: (u: string) => string = (u) => u): string {
  const out: string[] = []
  for (const rule of parseRules(css)) {
    if (!selectors.some((s) => matches(rule.selector, s))) continue
    const body = rule.body.replace(/url\(([^)]+)\)/g, (_m, u: string) => `url(${resolveUrl(u.replace(/^["']|["']$/g, ''))})`)
    out.push(`${rewritePseudo(rule.selector)} {\n  ${body}\n}`)
  }
  if (out.length === 0) throw new Error(`no portal rule matches ${selectors.join(', ')}`)
  return out.join('\n\n')
}
