#!/usr/bin/env python3
"""prompt_negation.py — when removing a thing from a shot, DELETE the noun. Do not negate it.

THE RENDER THIS COST. A clip came back with a cricket bat hanging unsupported in mid-air
and a stump materialising out of a hand. The redo added

    no cricket bat anywhere in frame, no stumps

to the Avoid list and changed nothing else. The prompt still opened with "a beach cricket
pitch marked out on flat wet sand, three wooden stumps driven into the sand, a worn
cricket bat leaning against them", and still directed "picks up the bat mid-verse". Two
further draws came back with the bat. The model was not ignoring the instruction — it was
obeying the DESCRIPTION, which is longer, earlier and concrete, while the prohibition is
one clause of a trailing list. The take that finally worked deleted the nouns outright
and put a folding canvas chair and a tea flask in the scene instead.

AND A PROHIBITION IS ITSELF A REFERENCE. A style negative reading "no children, no
minors" was refused outright for *"HIGH risk: Minor/child reference detected (match:
children)"*. The filter matches the WORD, not the intent. So a noun surviving ONLY inside
an Avoid clause is also a failure, for a second and independent reason.

Both point the same way: name what IS in the frame, and delete what is not.

WHY THIS TAKES AN EXPLICIT LIST rather than inferring the contradiction. A general
"prohibits X while describing X" linter was built first and thrown away: it flagged 189
contradictions across the 16 prompts of a film that shipped, and a narrowed version still
flagged 11 of 16. Every one was an adjective or a camera term — "flat" in "flat wet sand"
against "no flat-on framing", "wide" in "open wide" against "no empty establishing wide".
Word matching cannot tell a scene object from a modifier, and a gate that cries wolf on
the happy path is one people learn to click through. The operator knows which nouns they
are removing; asking is more reliable than guessing, and cannot produce a false positive.

Usage:
  prompt_negation.py --contract build/submit-contract.json --remove bat,stump[,...]
                     [--window w03] [--json]
  prompt_negation.py --text "..." --remove bat,stump

Exit 0 the nouns are gone · 4 at least one survives · 2 bad input
"""
from __future__ import annotations

import argparse
import json
import os
import re
import sys

# A clause is a prohibition when a negation marker opens it. Used only to explain WHERE a
# surviving noun sits, since both places are failures.
NEGATIONS = ("must not", "should not", "never", "without", "avoid", "remove the",
             "remove any", "no ", "not ")
CLAUSE_SPLIT = re.compile(r"[.;\n]|,(?=\s*(?:no |not |never |without |avoid ))", re.I)


def is_prohibition(clause: str) -> bool:
    head = clause.strip().lower()
    return any(head.startswith(m) or f" {m}" in f" {head}"[:40] for m in NEGATIONS)


def survivals(prompt: str, nouns: list[str]) -> list[dict]:
    """Every clause of `prompt` that still names one of `nouns`.

    Whole words only, plus a trailing 's'. Substrings would fire on "battered" for
    "bat" — which is a real word in these prompts and not the thing being removed.
    """
    out = []
    clauses = [c.strip() for c in CLAUSE_SPLIT.split(prompt) if c.strip()]
    for noun in nouns:
        pattern = re.compile(rf"\b{re.escape(noun)}(?:e?s)?\b", re.I)
        for clause in clauses:
            if pattern.search(clause):
                out.append({
                    "noun": noun,
                    "where": "prohibition" if is_prohibition(clause) else "description",
                    "clause": clause,
                })
    return out


WHY = {
    "description": ("the model renders what the prompt DESCRIBES. A trailing prohibition "
                    "loses to an earlier, longer, concrete description every time"),
    "prohibition": ("a prohibition is still a REFERENCE — the content filter matches the "
                    "word, not the intent, and refused a whole sheet over \"no children\""),
}


def main() -> None:
    ap = argparse.ArgumentParser()
    ap.add_argument("--contract", help="submit-contract.json, or any {windows:[{id,prompt}]}")
    ap.add_argument("--text", help="check one prompt directly")
    ap.add_argument("--window", default="", help="check only this window id")
    ap.add_argument("--remove", required=True,
                    help="comma-separated nouns that must be GONE, e.g. bat,stump,cricket")
    ap.add_argument("--json", action="store_true")
    args = ap.parse_args()

    nouns = [n.strip().lower() for n in args.remove.split(",") if n.strip()]
    if not nouns:
        print("prompt_negation: --remove needs at least one noun", file=sys.stderr)
        raise SystemExit(2)

    if args.text:
        prompts = [("<text>", args.text)]
    elif args.contract:
        if not os.path.isfile(args.contract):
            print(f"prompt_negation: not found: {args.contract}", file=sys.stderr)
            raise SystemExit(2)
        doc = json.load(open(args.contract, encoding="utf-8"))
        windows = doc["windows"] if isinstance(doc, dict) and "windows" in doc else doc
        prompts = [(str(w.get("id")), str(w.get("prompt", ""))) for w in windows
                   if not args.window or str(w.get("id")) == args.window]
        if not prompts:
            print(f"prompt_negation: no window {args.window!r} in {args.contract}",
                  file=sys.stderr)
            raise SystemExit(2)
    else:
        print("prompt_negation: give --contract or --text", file=sys.stderr)
        raise SystemExit(2)

    report = [{"id": pid, **hit} for pid, prompt in prompts
              for hit in survivals(prompt, nouns)]

    if args.json:
        print(json.dumps({"checked": len(prompts), "remove": nouns,
                          "survivals": report}, indent=2))
    if not report:
        if not args.json:
            print(f"prompt_negation: {', '.join(nouns)} gone from "
                  f"{len(prompts)} prompt(s)")
        return

    print(f"prompt_negation: REFUSED — {len(report)} surviving mention(s) of "
          f"{', '.join(nouns)}:", file=sys.stderr)
    for item in report:
        print(f"\n  {item['id']}  \"{item['noun']}\" survives in a {item['where']}",
              file=sys.stderr)
        print(f"    …{item['clause'][:130]}…", file=sys.stderr)
        print(f"    why that fails: {WHY[item['where']]}", file=sys.stderr)
    print("\n  DELETE the noun and put something ELSE in the scene. The redo that "
          "finally worked\n  replaced the cricket gear with a folding canvas chair and "
          "a tea flask — no negation\n  anywhere in the prompt.", file=sys.stderr)
    raise SystemExit(4)


if __name__ == "__main__":
    main()
