#!/usr/bin/env python3
"""Apply PropHog foreclosure-host patches to baked Next.js chunks."""
from __future__ import annotations

import re
import sys
from pathlib import Path


def patch_alts(path: Path, groups: list[list[tuple[str, str]]], label: str, required: bool = True) -> None:
    t = path.read_text()
    original = t
    for alts in groups:
        applied = False
        for old, new in alts:
            if new in t and old not in t:
                applied = True
                break
            if old in t:
                t = t.replace(old, new, 1)
                applied = True
                break
        if not applied:
            preview = alts[0][0][:120]
            if required:
                raise SystemExit(f"{label}: pattern missing in {path.name}:\n  {preview}…")
            print(f"{label}: skip {path.name} (no matching pattern)")
            return
    if t != original:
        path.write_text(t)
        print(f"patched {path.relative_to(path.parents[5]) if len(path.parents) > 5 else path}")
    else:
        print(f"unchanged {path.name}")


def patch_regex(path: Path, patterns: list[tuple[str, callable]], label: str) -> None:
    t = path.read_text()
    original = t
    for pattern, repl in patterns:
        rx = re.compile(pattern)
        m = rx.search(t)
        if not m:
            raise SystemExit(f"{label}: regex missing in {path.name}:\n  {pattern[:120]}")
        t = rx.sub(repl, t, count=1)
    if t != original:
        path.write_text(t)
        print(f"patched {path.relative_to(path.parents[5]) if len(path.parents) > 5 else path}")
    else:
        print(f"unchanged {path.name}")


def chunk_from_html(html: str, pattern: str) -> str | None:
    m = re.search(pattern, html)
    return m.group(0) if m else None


def main() -> None:
    ui = Path(sys.argv[1]) if len(sys.argv) > 1 else Path(
        "/Volumes/Projects/Jagjeet Singh/Chris -USA/digital.ocean.server/app-server/iul.prophog2.com/ui"
    )
    chunks = ui / "_next/static/chunks"
    fc_index = ui / "foreclosure/index.html"
    fc_html = fc_index.read_text() if fc_index.exists() else ""

    layout_name = chunk_from_html(fc_html, r"app/layout-[a-f0-9]+\.js") or "app/layout-39a52376969834e2.js"
    layout = chunks / layout_name
    patch_alts(layout, [[(
        'function s(n){let{children:e}=n,t=(0,i.usePathname)();return(null==t?void 0:t.startsWith("/foreclosure"))?(0,r.jsx)(r.Fragment,{children:e}):(0,r.jsx)(u.Vw,{children:e})}',
        'function s(n){let{children:e}=n,t=(0,i.usePathname)(),o=null!=t&&t.startsWith("/foreclosure");if(!o&&"undefined"!=typeof window&&window.location.hostname.startsWith("foreclosure.")){let p=window.location.pathname;o="/"===p||p.startsWith("/case")||p.startsWith("/pipelines")}return o?(0,r.jsx)(r.Fragment,{children:e}):(0,r.jsx)(u.Vw,{children:e})}',
    )]], "layout")

    # Shared foreclosure shell chunk was historically 629-*.js; round 12.5+
    # rebuilds emit a different numeric id (e.g. 75-*.js). Prefer the chunk
    # referenced from foreclosure/index.html that isn't a framework/app page.
    shell629_name = chunk_from_html(fc_html, r"(?:629|75)-[a-f0-9]+\.js")
    shell = chunks / shell629_name if shell629_name else None
    if not shell or not shell.exists():
        candidates = sorted(
            list(chunks.glob("629-*.js")) + list(chunks.glob("75-*.js")),
            key=lambda p: p.stat().st_mtime,
            reverse=True,
        )
        shell = candidates[0] if candidates else None
    if shell is None or not shell.exists():
        # Last resort: first top-level chunk that owns the Cases/Pipelines nav.
        shell = None
        for p in sorted(chunks.glob("*.js"), key=lambda x: x.stat().st_mtime, reverse=True):
            if "/" in str(p.relative_to(chunks)):
                continue
            txt = p.read_text(errors="ignore")
            if "/foreclosure/pipelines" in txt and "rounded-full border px-3.5" in txt:
                shell = p
                break
    if shell is None or not shell.exists():
        raise SystemExit("foreclosure shell chunk (629/75) missing")

    def nav_repl_pills(m: re.Match) -> str:
        """Round-9+ pill nav (Cases / Pipelines)."""
        arr, on_var, link_ident = m.group(1), m.group(2), m.group(3)
        on_cls = (
            f'{on_var}?"border-stone-900 bg-stone-900 text-white"'
            f':"border-stone-300 bg-white text-stone-600 hover:border-stone-500 hover:text-stone-900"'
        )
        return (
            f'children:{arr}.map(e=>{{'
            f'let f="undefined"!=typeof window&&window.location.hostname.startsWith("foreclosure.");'
            f'let h="/foreclosure/pipelines"===e.href?"/pipelines/":"/";'
            f'let p="undefined"!=typeof window?window.location.pathname:String(n||"");'
            f'let pipe="/foreclosure/pipelines"===e.href;'
            f'let {on_var}=pipe?(null!=n&&(n==="/foreclosure/pipelines"||n.startsWith("/foreclosure/pipelines/"))||"/pipelines"===p||p.startsWith("/pipelines")):'
            f'(n===e.href||n.startsWith(e.href+"/")||"/"===p||p.startsWith("/case"))&&!(null!=n&&n.startsWith("/foreclosure/pipelines")||p.startsWith("/pipelines"));'
            f'return f?(0,r.jsx)("a",{{href:h,className:"rounded-full border px-3.5 py-1 text-[13px] font-semibold transition ".concat({on_cls}),'
            f'onClick:x=>{{x.preventDefault();window.location.href=h}},children:e.label}},e.href)'
            f':(0,r.jsx)({link_ident}.default,{{href:e.href,className:"rounded-full border px-3.5 py-1 text-[13px] font-semibold transition ".concat({on_cls}),children:e.label}},e.href)}})'
        )

    def nav_repl(m: re.Match) -> str:
        arr, ident = m.group(1), m.group(2)
        cls = (
            f'(n===e.href||n.startsWith(e.href+"/"))&&!{arr}.some(t=>t.href.length>e.href.length'
            f'&&(n===t.href||n.startsWith(t.href+"/")))?"font-semibold text-stone-900":"text-stone-500 hover:text-stone-800"'
        )
        return (
            f'children:{arr}.map(e=>{{let f="undefined"!=typeof window&&window.location.hostname.startsWith("foreclosure.");'
            f'let h="/foreclosure/pipelines"===e.href?"/pipelines/":"/";'
            f'let p="undefined"!=typeof window?window.location.pathname:String(n||"");'
            f'let pipe="/foreclosure/pipelines"===e.href;'
            f'let a=pipe?(null!=n&&(n==="/foreclosure/pipelines"||n.startsWith("/foreclosure/pipelines/"))||"/pipelines"===p||p.startsWith("/pipelines")):'
            f'(n===e.href||n.startsWith(e.href+"/")||"/"===p||p.startsWith("/case"))&&!(null!=n&&n.startsWith("/foreclosure/pipelines")||p.startsWith("/pipelines"));'
            f'return f?(0,r.jsx)("a",{{href:h,className:"backlit-sm rounded px-0.5 ".concat(a?"font-semibold text-stone-900":"text-stone-500 hover:text-stone-800"),'
            f'onClick:t=>{{t.preventDefault();window.location.href=h}},children:e.label}},e.href):(0,r.jsx)({ident}.default,'
            f'{{href:e.href,className:"backlit-sm rounded px-0.5 ".concat({cls}),children:e.label}},e.href)}})'
        )

    def list_repl(m: re.Match) -> str:
        fn, req, fx = m.group(1), m.group(2), m.group(3)
        return (
            f'async function {fn}(){{if(!(0,r.kP)())return(await {fx}("cases.json")).cases;'
            f'try{{return(await {req}("/foreclosures")).cases}}catch(e){{if(e&&e.status===401)return(await {fx}("cases.json")).cases;throw e}}}}'
        )

    def detail_repl(m: re.Match) -> str:
        fn, req, fx = m.group(1), m.group(2), m.group(3)
        return (
            f'async function {fn}(e){{if(!(0,r.kP)()||String(e).startsWith("sample-"))return(await {fx}("".concat(e,".json"))).case;'
            f'try{{return(await {req}("/foreclosures/".concat(e))).case}}catch(t){{if(t&&t.status===401)return(await {fx}("".concat(e,".json"))).case;throw t}}}}'
        )

    def upload_repl(m: re.Match) -> str:
        rej, err = m.group(1), m.group(2)
        return (
            f'i.status>=200&&i.status<300?n(e):{rej}(new {err}(401===i.status?"Sign in to upload — open /index.php, sign in, then return here.":'
            f'"object"==typeof e&&null!==e&&"error"in e?String(e.error):"upload failed (HTTP ".concat(i.status,")"),i.status))'
        )

    shell_txt = shell.read_text()
    if "hostname.startsWith(\"foreclosure.\")" in shell_txt and "status===401" in shell_txt:
        print(f"unchanged {shell.name}")
    else:
        # Prefer pill-nav pattern (src_12+); fall back to older text-link nav.
        pill_nav = (
            r'children:([a-z])\.map\(e=>\{let ([a-z])=\(n===e\.href\|\|n\.startsWith\(e\.href\+"/"\)\)&&!\1\.some\(t=>t\.href\.length>e\.href\.length&&\(n===t\.href\|\|n\.startsWith\(t\.href\+"/"\)\)\);'
            r'return\(0,r\.jsx\)\(([a-z])\.default,\{href:e\.href,className:"rounded-full border px-3\.5 py-1 text-\[13px\] font-semibold transition "\.concat\(\2\?"border-stone-900 bg-stone-900 text-white":"border-stone-300 bg-white text-stone-600 hover:border-stone-500 hover:text-stone-900"\),children:e\.label\},e\.href\)\}\)'
        )
        old_nav = (
            r'children:([a-z])\.map\(e=>\(0,r\.jsx\)\(([a-z])\.default,\{href:e\.href,className:"backlit-sm rounded px-0\.5 "\.concat\(.+?\),children:e\.label\},e\.href\)\)'
        )
        nav_pat, nav_fn = (pill_nav, nav_repl_pills) if re.search(pill_nav, shell_txt) else (old_nav, nav_repl)
        patch_regex(shell, [
            (nav_pat, nav_fn),
            (r'async function ([a-z])\(\)\{return\(0,r\.kP\)\(\)\?\(await ([a-z])\("/foreclosures"\)\)\.cases:\(await ([a-z])\("cases\.json"\)\)\.cases\}',
             list_repl),
            (r'async function ([a-z])\(e\)\{return\(0,r\.kP\)\(\)\?\(await ([a-z])\("/foreclosures/"\.concat\(e\)\)\)\.case:\(await ([a-z])\(""\.concat\(e,"\.json"\)\)\)\.case\}',
             detail_repl),
            (r'i\.status>=200&&i\.status<300\?n\(e\):([a-z])\(new ([a-z])\("object"==typeof e&&null!==e&&"error"in e\?String\(e\.error\):"upload failed \(HTTP "\.concat\(i\.status,"\)"\),i\.status\)\)',
             upload_repl),
        ], "629")

    name536 = chunk_from_html(fc_html, r"536-[a-f0-9]+\.js")
    app536 = chunks / name536 if name536 and (chunks / name536).exists() else None
    if app536 is None:
        found = sorted(chunks.glob("536-*.js"), key=lambda p: p.stat().st_mtime, reverse=True)
        app536 = found[0] if found else None
    if app536:
        patch_alts(app536, [[(
            'f&&((0,l.LP)()||(window.location.href="/"),(0,l.GJ)().then(d))',
            'f&&("undefined"==typeof window||!window.location.hostname.startsWith("foreclosure."))&&((0,l.LP)()||(window.location.href="/"),(0,l.GJ)().then(d))',
        )]], "536")

    page_name = chunk_from_html(fc_html, r"app/foreclosure/page-[a-f0-9]+\.js")
    pages = []
    if page_name:
        named = chunks / "app/foreclosure" / page_name.split("/")[-1]
        if named.exists():
            pages = [named]
    if not pages:
        pages = sorted((chunks / "app/foreclosure").glob("page-*.js"))
    if not pages:
        raise SystemExit("foreclosure page chunk missing")
    def open_repl(m: re.Match) -> str:
        ident = m.group(1)
        end = m.group(2) or ";"
        return (
            f'{ident}=t=>{{"undefined"!=typeof window&&window.location.hostname.startsWith("foreclosure.")?'
            f'window.location.href="/case/?id=".concat(encodeURIComponent(t)):e.push("/foreclosure/case?id=".concat(t))}}{end}'
        )

    patch_regex(pages[0], [
        (r'([a-zA-Z_])=t=>e\.push\("/foreclosure/case\?id="\.concat\(t\)\)([;,])', open_repl),
    ], "foreclosure page open")

    # Sign-in CTA — jsx ident letter varies by build.
    page_txt = pages[0].read_text()
    signin_patched = False
    for ident in ("s", "a", "n", "r"):
        old = (
            f'(0,{ident}.jsx)("a",{{href:"/",className:"backlit-sm mt-3 inline-block rounded-lg bg-stone-900 px-4 py-2 text-sm font-medium text-white",children:"Sign in to upload"}})'
        )
        new = (
            f'(0,{ident}.jsx)("a",{{href:"undefined"!=typeof window&&window.location.hostname.startsWith("foreclosure.")?"/index.php":"/",className:"backlit-sm mt-3 inline-block rounded-lg bg-stone-900 px-4 py-2 text-sm font-medium text-white",children:"Sign in to upload"}})'
        )
        if old in page_txt:
            pages[0].write_text(page_txt.replace(old, new, 1))
            print(f"patched foreclosure page signin ({ident})")
            signin_patched = True
            break
    if not signin_patched:
        # Softer fallback: only rewrite the href:"/" immediately before the CTA label.
        soft = re.sub(
            r'href:"/"((?:,className:"[^"]*")?,children:"Sign in to upload")',
            r'href:"undefined"!=typeof window&&window.location.hostname.startsWith("foreclosure.")?"/index.php":"/"\1',
            page_txt,
            count=1,
        )
        if soft != page_txt:
            pages[0].write_text(soft)
            print("patched foreclosure page signin (soft)")
            signin_patched = True
    if not signin_patched:
        raise SystemExit("foreclosure page signin: pattern missing")

    # PropHog: "Open county leads" via DOM script (do NOT patch React page
    # chunks — that causes hydration #418/#423 and can blank the toolbar).
    extras_js = Path(__file__).resolve().parent / "ui-extras/js/fc-county-leads-btn.js"
    dest_js_dir = ui / "foreclosure/js"
    dest_js = dest_js_dir / "fc-county-leads-btn.js"
    if extras_js.exists():
        dest_js_dir.mkdir(parents=True, exist_ok=True)
        dest_js.write_text(extras_js.read_text())
        print(f"copied {dest_js.relative_to(ui)}")
    thumbs_src = Path(__file__).resolve().parent / "ui-extras/js/fc-board-thumbs.js"
    thumbs_dest = dest_js_dir / "fc-board-thumbs.js"
    if thumbs_src.exists():
        dest_js_dir.mkdir(parents=True, exist_ok=True)
        thumbs_dest.write_text(thumbs_src.read_text())
        print(f"copied {thumbs_dest.relative_to(ui)}")
    for rel in (
        "foreclosure/pipelines/index.html",
        "foreclosure/index.html",
        "foreclosure/case/index.html",
    ):
        html_path = ui / rel
        if not html_path.exists():
            continue
        ht = html_path.read_text()
        tags = []
        if dest_js.exists() and "fc-county-leads-btn.js" not in ht:
            tags.append('<script src="/ui/foreclosure/js/fc-county-leads-btn.js?v=3" defer></script>')
        if thumbs_dest.exists() and "fc-board-thumbs.js" not in ht:
            tags.append('<script src="/ui/foreclosure/js/fc-board-thumbs.js?v=1" defer></script>')
        if tags:
            if "</body>" not in ht:
                raise SystemExit(f"{rel} missing </body>")
            html_path.write_text(ht.replace("</body>", "\n".join(tags) + "\n</body>", 1))
            print(f"patched {rel} (prop hog ui scripts)")
        else:
            print(f"unchanged {rel} (prop hog ui scripts present)")
    # Keep county-leads cache-bust current when already present
    for rel in (
        "foreclosure/pipelines/index.html",
        "foreclosure/index.html",
        "foreclosure/case/index.html",
    ):
        html_path = ui / rel
        if not html_path.exists():
            continue
        ht = html_path.read_text()
        import re as _re
        updated = _re.sub(
            r'src="/ui/foreclosure/js/fc-county-leads-btn\.js(?:\?[^"]*)?"',
            'src="/ui/foreclosure/js/fc-county-leads-btn.js?v=3"',
            ht,
        )
        updated = _re.sub(
            r'src="/ui/foreclosure/js/fc-board-thumbs\.js(?:\?[^"]*)?"',
            'src="/ui/foreclosure/js/fc-board-thumbs.js?v=1"',
            updated,
        )
        if updated != ht:
            html_path.write_text(updated)
            print(f"patched {rel} (script cache-bust)")

    # legacy block removed — county + thumbs handled above
    if False:
        pass
    # Strip any prior React-chunk injection of the label (idempotent cleanup)
    for pipep in sorted((chunks / "app/foreclosure/pipelines").glob("page-*.js")):
        pt = pipep.read_text()
        junk = (
            '(0,n.jsx)("a",{href:"/county-leads/",'
            'className:"backlit-sm rounded-lg border border-emerald-300 bg-emerald-50 px-3 py-1.5 text-xs font-semibold text-emerald-900",'
            'onClick:e=>{e.preventDefault();'
            'window.location.href="undefined"!=typeof window&&window.location.hostname.startsWith("foreclosure.")'
            '?"/county-leads/":"/ui/foreclosure/county-leads/"},'
            'children:"Open county leads"}),'
        )
        cleaned = pt
        for ident in ("n", "s", "a", "r"):
            j = junk.replace("(0,n.jsx)", f"(0,{ident}.jsx)")
            if j in cleaned:
                cleaned = cleaned.replace(j, "", 1)
        if cleaned != pt:
            pipep.write_text(cleaned)
            print(f"removed React-chunk county link from {pipep.name}")

    case_html_path = ui / "foreclosure/case/index.html"
    case_html = case_html_path.read_text() if case_html_path.exists() else ""
    case_name = chunk_from_html(case_html, r"app/foreclosure/case/page-[a-f0-9]+\.js")
    case_pages = list(sorted((chunks / "app/foreclosure/case").glob("page-*.js")))
    if case_name:
        named = chunks / "app/foreclosure/case" / case_name.split("/")[-1]
        if named.exists():
            case_pages = [named] + [p for p in case_pages if p != named]
    case_old = lambda ident: (
        f'(0,{ident}.jsx)(l.default,{{href:"/foreclosure",className:"backlit-sm shrink-0 rounded px-1 text-sm text-stone-500 hover:text-stone-800",children:"← All cases"}})'
    )
    case_old_legacy = lambda ident: (
        f'(0,{ident}.jsx)(l.default,{{href:"/foreclosure",className:"backlit-sm rounded px-1 text-sm text-stone-500 hover:text-stone-800",children:"← All cases"}})'
    )
    case_new = lambda ident, cls: (
        f'(0,{ident}.jsx)("a",{{href:"undefined"!=typeof window&&window.location.hostname.startsWith("foreclosure.")?"/":"/ui/foreclosure/",className:"{cls}",onClick:e=>{{e.preventDefault(),"undefined"!=typeof window&&window.location.hostname.startsWith("foreclosure.")?window.location.href="/":window.location.href="/ui/foreclosure/"}},children:"← All cases"}})'
    )
    for casep in case_pages:
        patch_alts(casep, [[
            (case_old("n"), case_new("n", "backlit-sm shrink-0 rounded px-1 text-sm text-stone-500 hover:text-stone-800")),
            (case_old("s"), case_new("s", "backlit-sm shrink-0 rounded px-1 text-sm text-stone-500 hover:text-stone-800")),
            (case_old("a"), case_new("a", "backlit-sm shrink-0 rounded px-1 text-sm text-stone-500 hover:text-stone-800")),
            (case_old_legacy("n"), case_new("n", "backlit-sm rounded px-1 text-sm text-stone-500 hover:text-stone-800")),
            (case_old_legacy("s"), case_new("s", "backlit-sm rounded px-1 text-sm text-stone-500 hover:text-stone-800")),
            (case_old_legacy("a"), case_new("a", "backlit-sm rounded px-1 text-sm text-stone-500 hover:text-stone-800")),
        ]], "case page", required=False)

    # Round 10+: SkipTracePanel is built into the Next export — do NOT inject
    # ui-extras/js/fc-skiptrace.js (that would double-render Find phones).
    for html_path in (
        ui / "foreclosure/case/index.html",
        ui / "foreclosure/pipelines/index.html",
    ):
        if not html_path.exists():
            continue
        ht = html_path.read_text()
        cleaned = re.sub(r'<link[^>]*fc-skiptrace\.css[^>]*/?>', "", ht)
        cleaned = re.sub(r'<script[^>]*fc-skiptrace\.js[^>]*>\s*</script>', "", cleaned)
        if cleaned != ht:
            html_path.write_text(cleaned)
            print(f"removed skiptrace overlay from {html_path.name}")

    print("FC_PATCH_OK")


if __name__ == "__main__":
    main()
