"""Structure and style guard for this site. Run: python3 check.py (exit 1 on any violation).
Each rule was written before the page change it guards and seen failing first.
Content rules (wording kept off the public site) live in check_private.py, which is not published."""
import pathlib, re, subprocess, sys

ROOT = pathlib.Path(__file__).parent
NOINDEX = '<meta name="robots" content="noindex">'
RAW_BANNED = ["<table", "<b>", "<strong>", "<title>Jonghyun Beik — AI Agent"]  # no tables, no bold lead text
CSS_NEEDED = ("max-width: 480px", "@media print", "grid-template-columns", "min-width: 0", "pre-wrap")
CSS_BANNED = ["h3 a { text-decoration: none"]                  # links must look like links on phones
HOME_ORDER = ["built", "llm", "other", "why", "how", "experience"]  # overview first: what was built
REQUIRED_ALL = ['class="artifact"']                            # every page leads with a real artifact
GITIGNORE_NEEDED = ["LEDGER.md", "check_private.py"]           # private notes never deploy
ACCENT = "39729e"                                              # one muted blue: links and the "built by me" boxes only
ALLOWED_TINTS = {ACCENT, "fdfdfc"}                             # plus a near-white page background
CSS_NEEDED += ("#fdfdfc", "#171717", "#" + ACCENT)


def violations(root=ROOT):
    out = []
    pages = sorted(root.rglob("*.html"))
    css = root / "style.css"
    if not pages:
        out.append("no html pages")
    if not css.exists():
        out.append("missing style.css")
    else:
        s = css.read_text()
        out += [f"style.css: banned '{b}'" for b in CSS_BANNED if b in s]
        out += [f"style.css: missing '{n}'" for n in CSS_NEEDED if n not in s]
    for f in pages + ([css] if css.exists() else []):
        text = f.read_text()
        for h in re.findall(r"#([0-9a-fA-F]{6}|[0-9a-fA-F]{3})\b", text):
            h = h.lower()
            h = "".join(c * 2 for c in h) if len(h) == 3 else h
            if not (h[0:2] == h[2:4] == h[4:6]) and h not in ALLOWED_TINTS:
                out.append(f"{f.name}: non-grey color #{h}")
        if f.suffix != ".html":
            continue
        rel = f.relative_to(root)
        if NOINDEX not in text:
            out.append(f"{rel}: missing noindex")
        if re.search(r"<h2>\s*\d", text):
            out.append(f"{rel}: numbered section heading")
        out += [f"{rel}: banned markup '{w}'" for w in RAW_BANNED if w in text]
        out += [f"{rel}: missing '{w}'" for w in REQUIRED_ALL if w not in text]
        if rel.name != "index.html" and ACCENT in text:
            out.append(f"{rel}: accent outside links (case pages get it only through CSS links)")
        for ref in re.findall(r'(?:href|src)="([^"#:]+)(?:#[^"]*)?"', text):
            if not (f.parent / ref).resolve().exists():
                out.append(f"{rel}: broken link {ref}")
    home = root / "index.html"
    if home.exists():
        t = home.read_text()
        pos = [t.find(f'id="{i}"') for i in HOME_ORDER]
        if -1 in pos or pos != sorted(pos):
            out.append(f"index.html: section order must be {HOME_ORDER}")
        if t.count(ACCENT) < 1:
            out.append("index.html: map must mark my parts with the accent")
    gi = root / ".gitignore"
    gtxt = gi.read_text() if gi.exists() else ""
    out += [f".gitignore: missing '{n}'" for n in GITIGNORE_NEEDED if n not in gtxt]
    pdf = root / "resume.pdf"
    if not pdf.exists():
        out.append("missing resume.pdf")
    elif "jong0917@yonsei.ac.kr" not in subprocess.run(["pdftotext", str(pdf), "-"], capture_output=True, text=True).stdout:
        out.append("resume.pdf: missing site email")
    try:
        import check_private
        out += check_private.violations(root)
    except ImportError:
        pass
    return out


if __name__ == "__main__":
    v = violations()
    if v:
        print("\n".join(v))
        sys.exit(1)
    print(f"OK {len(list(ROOT.rglob('*.html')))} files")
