"""Create a reviewable API payload from real run results; never send it."""
import argparse
import json
from pathlib import Path
import re

root = Path(__file__).resolve().parent
parser = argparse.ArgumentParser()
parser.add_argument("--username", required=True)
parser.add_argument("--code-link", required=True)
parser.add_argument("--backend", choices=["codex", "mlx"], default="codex")
args = parser.parse_args()
if not args.code_link.startswith("https://huggingface.co/spaces/") or not args.code_link.endswith("/tree/main"):
    parser.error("Provide the public Hugging Face Space source link ending /tree/main")
run_dir = root / ("codex-runs" if args.backend == "codex" else "runs")
answers = json.loads((run_dir / "answers.json").read_text())
questions = json.loads((root / "questions.json").read_text())
expected = {row["task_id"] for row in questions}
seen = {row["task_id"] for row in answers}
if expected != seen or len(answers) != len(expected):
    parser.error(f"Expected {len(expected)} unique question results; found {len(answers)}")
questions_by_id = {row["task_id"]: row["question"] for row in questions}
formatted_answers = []
format_changes = []
for row in answers:
    question = questions_by_id[row["task_id"]]
    raw = row["submitted_answer"]
    answer = raw
    requests_comma_list = bool(re.search(r"comma[\s-]+(?:separated|delimited)\s+list", question, re.IGNORECASE))
    forbids_spaces = bool(re.search(r"without\s+(?:any\s+)?spaces|no\s+spaces|do\s+not\s+(?:use|include|add)\s+spaces", question, re.IGNORECASE))
    if requests_comma_list and not forbids_spaces:
        answer = ", ".join(part.strip() for part in raw.split(","))
    formatted_answers.append({"task_id": row["task_id"], "submitted_answer": answer})
    if answer != raw:
        format_changes.append({"task_id": row["task_id"], "raw_answer": raw, "formatted_answer": answer, "rule": "Canonical comma-list delimiter whitespace; content preserved."})
payload = {"username": args.username, "agent_code": args.code_link, "answers": formatted_answers}
path = run_dir / "submission.json"
path.write_text(json.dumps(payload, indent=2, ensure_ascii=False))
write_audit = run_dir / "submission-formatting.json"
write_audit.write_text(json.dumps(format_changes, indent=2, ensure_ascii=False))
print(f"Prepared {len(answers)} generated answers in {path}; {len(format_changes)} delimiter-whitespace changes logged in {write_audit}; no submission made.")
