"""DV-P: plant up to 3 defects (R, U, T) per incumbent draft, per PREREG-ADDENDUM-1. Writes io_planted/ and
raw/plants.json. ground.py is then re-run on io_planted (separate shell step) and confirm_plants() checks it."""
from __future__ import annotations
import os

import hashlib
import json
import random
import re
import shutil
import sys

import ws4lib as L

NUM = re.compile(r"\d[\d,]*(?:\.\d+)?")


def _double(numstr: str) -> str:
    raw = numstr.replace(",", "")
    if "." in raw:
        dec = len(raw.split(".")[1])
        v = float(raw) * 2
        out = f"{v:,.{dec}f}" if "," in numstr else f"{v:.{dec}f}"
    else:
        v = int(raw) * 2
        out = f"{v:,}" if "," in numstr else str(v)
    return out


def eligible(u, domain):
    if u["cat"] != "clean" or u["n_units_on_line"] != 1 or not u["urls"]:
        return set()
    if not any(t in L.ground.SOURCED_TAGS for t in u["tags"]):
        return set()
    types = {"U"}
    if u["receipt"]:
        types.add("R")
    if "THIRD-PARTY" in u["tags"] and "VENDOR-CLAIMED" not in u["tags"]:
        ok = True
        for url in u["urls"]:
            un = L.ground._unwrap_wayback(url)
            t = L.ground.vd.classify_url(un, domain)
            if t in ("own", "vendor_pr") or un != url or L.ground._is_linkedin_company(un):
                ok = False
        if ok:
            types.add("T")
    return types


def mutate(line: str, u: dict, typ: str, slug: str, domain: str) -> tuple[str, dict]:
    blk = line.index("[[")
    pre, block = line[:blk], line[blk:]
    info = {}
    if typ == "R":
        m = re.search(r'receipt:\s*"([^"]{8,})"', block)
        rec = m.group(1)
        nm = NUM.search(rec)
        if nm:
            old = nm.group(0)
            new = _double(old)
            rec2 = rec[:nm.start()] + new + rec[nm.end():]
            if old in pre:
                pre = pre.replace(old, new, 1)
                info["claim_text_changed"] = True
            info.update({"how": "number doubled", "old": old, "new": new})
        else:
            wm = re.search(r"\b[A-Za-z]{5,}\b", rec)
            rec2 = rec[:wm.start()] + "industry-leading " + rec[wm.start():]
            info.update({"how": "inserted 'industry-leading'"})
        block = block[:m.start(1)] + rec2 + block[m.end(1):]
    elif typ == "U":
        url = u["urls"][0]
        h = hashlib.sha256((slug + str(u["pos"])).encode()).hexdigest()[:8]
        newurl = f"https://{domain}/resources/{h}"
        lm = re.search(r"\[([^\[\]]*)\]\(" + re.escape(url), block)
        if lm:
            block = block[:lm.start()] + f"[{domain}/resources/{h}]({newurl}" + block[lm.end():]
        else:
            block = block.replace(url, newurl, 1)
        info.update({"how": "url replaced", "old": url, "new": newurl})
    elif typ == "T":
        block = block.replace("THIRD-PARTY", "VENDOR-CLAIMED", 1)
        info.update({"how": "THIRD-PARTY -> VENDOR-CLAIMED"})
    return pre + block, info


def main():
    plants = []
    for slug in L.slugs_for("incumbent"):
        text = L.load_draft("incumbent", slug)
        dj = json.loads((L.io_root("incumbent") / "runs" / slug / "stages" / "defects.json").read_text(encoding="utf-8"))
        domain = dj["domain"]
        units, _, _ = L.classify_units("incumbent", slug)
        rng = random.Random("20260921-" + slug)
        el = [(u, eligible(u, domain)) for u in units]
        chosen = set()
        lines = text.split("\n")
        for typ in ("R", "U", "T"):
            cands = [u for u, ts in el if typ in ts and u["line_idx"] not in chosen]
            if not cands:
                plants.append({"slug": slug, "type": typ, "skipped": "no eligible unit"})
                continue
            u = rng.choice(cands)
            chosen.add(u["line_idx"])
            newline, info = mutate(lines[u["line_idx"]], u, typ, slug, domain)
            lines[u["line_idx"]] = newline
            plants.append({"slug": slug, "type": typ, "line_idx": u["line_idx"], "orig_pos": u["pos"],
                           "orig_line": u["line"], "new_line": newline, **info})
        dst = L.io_root("planted") / "runs" / slug
        (dst / "stages").mkdir(parents=True, exist_ok=True)
        if not (dst / "bundle").exists():
            shutil.copytree(L.io_root("incumbent") / "runs" / slug / "bundle", dst / "bundle")
        (dst / "stages" / "dossier.md").write_text("\n".join(lines), encoding="utf-8")
    pend = L.io_root("planted") / "pending"
    pend.mkdir(parents=True, exist_ok=True)
    shutil.copy(L.io_root("incumbent") / "pending" / (os.environ["WS4_PLANT_SEED_VENDOR"] + ".json"), pend / (os.environ["WS4_PLANT_SEED_VENDOR"] + ".json"))
    (L.WS4 / "raw" / "plants.json").write_text(json.dumps(plants, indent=1), encoding="utf-8")
    print(len([p for p in plants if "skipped" not in p]), "plants;",
          len([p for p in plants if "skipped" in p]), "skipped")


def confirm():
    plants = json.loads((L.WS4 / "raw" / "plants.json").read_text(encoding="utf-8"))
    ok = 0
    for p in plants:
        if "skipped" in p:
            continue
        units, _, _ = L.classify_units("planted", p["slug"])
        on = [u for u in units if u["line_idx"] == p["line_idx"]]
        p["ground_cat"] = on[0]["cat"] if on else None
        p["ground_why"] = on[0]["why"] if on else None
        p["confirmed"] = bool(on) and on[0]["cat"] in ("ungrounded", "mistagged", "unresolved")
        p["planted_pos"] = on[0]["pos"] if on else None
        ok += p["confirmed"]
    (L.WS4 / "raw" / "plants.json").write_text(json.dumps(plants, indent=1), encoding="utf-8")
    print("confirmed", ok)


if __name__ == "__main__":
    confirm() if "--confirm" in sys.argv else main()
