#!/usr/bin/env python3
from pathlib import Path
import argparse, shutil, re, sys
parser=argparse.ArgumentParser(description="Create one deliberate WEB013 failure mutation in a disposable copy; no accessibility verdict is produced.")
parser.add_argument("--mutation",choices=["hide-focus","drop-restoration","pointer-only"],required=True)
parser.add_argument("--source",default="learner/starter")
parser.add_argument("--output",default="mutated")
a=parser.parse_args()
ROOT=Path(__file__).resolve().parent.parent
src=(ROOT/a.source).resolve(); out=(ROOT/a.output).resolve()
if not src.is_dir(): raise SystemExit(f"Source directory not found: {src}")
if out.exists(): shutil.rmtree(out)
shutil.copytree(src,out)
html=out/'index.html'; css=out/'styles.css'; js=out/'app.js'
if not all(p.is_file() for p in [html,css,js]): raise SystemExit("Mutation source must contain index.html, styles.css, and app.js")
if a.mutation=="hide-focus":
    before=css.read_text(encoding='utf-8')
    css.write_text(before+"\n/* MUTATION: suppress visible focus */\n:focus, :focus-visible { outline: none !important; box-shadow: none !important; }\n",encoding='utf-8')
elif a.mutation=="drop-restoration":
    text=js.read_text(encoding='utf-8')
    patch="\n/* MUTATION: override sensible restoration with an unrelated target after close. */\ndocument.querySelector('#filter-dialog')?.addEventListener('close', () => setTimeout(() => document.querySelector('#status')?.focus(), 0));\n"
    js.write_text(text+patch,encoding='utf-8')
elif a.mutation=="pointer-only":
    text=html.read_text(encoding='utf-8')
    pattern=r'<button\b([^>]*\bid=["\']apply-filters["\'][^>]*)>\s*Apply\s*</button>'
    repl='<div id="apply-filters" role="button" tabindex="0">Apply</div>'
    new,n=re.subn(pattern,repl,text,count=1,flags=re.I)
    if n!=1:
        shutil.rmtree(out,ignore_errors=True)
        raise SystemExit("pointer-only mutation target #apply-filters was not found exactly once; no mutation produced")
    html.write_text(new,encoding='utf-8')
    jt=js.read_text(encoding='utf-8')
    jt += "\n/* MUTATION: preserve pointer activation only; no Enter/Space keyboard handler is added. */\ndocument.querySelector('#apply-filters')?.addEventListener('click', () => document.querySelector('#filter-dialog')?.close('apply'));\n"
    js.write_text(jt,encoding='utf-8')
print(f"Created {a.mutation} mutation at {out}")
print("Predict the failure first, then run the mutated fixture and record direct observations. This script does not declare accessibility correctness.")
