from __future__ import annotations

import os
import json
import datetime


PLACEHOLDER_PATTERNS = [
    "TODO",
    "TBD",
    "XXX",
    "??",
]


def read_all_tex(project_root: str) -> str:
    """Read ALL .tex files in project (handles includes automatically)."""
    tex_content = ""
    for root, _, files in os.walk(project_root):
        for f in files:
            if f.endswith(".tex"):
                try:
                    with open(os.path.join(root, f), "r", encoding="utf-8", errors="ignore") as fh:
                        tex_content += fh.read() + "\n"
                except:
                    pass
    return tex_content


def gate_row26_refs(project_root: str) -> dict:
    tex = read_all_tex(project_root)

    # ---- Bibliography detection (robust) ----
    has_bibliography = any(x in tex for x in [
        "\\bibliography",
        "\\begin{thebibliography}",
        "\\printbibliography"
    ])

    # ---- Acknowledgments detection ----
    has_ack = ("acknowledg" in tex.lower())

    # ---- Copyright detection ----
    has_copyright = (
        "Ronald L. Alexander" in tex and
        ("©" in tex or "(c)" in tex.lower())
    )

    # ---- Placeholder detection ----
    placeholder_hits = [p for p in PLACEHOLDER_PATTERNS if p in tex]
    n_placeholders = len(placeholder_hits)

    pass_rule = has_bibliography and has_ack and has_copyright and (n_placeholders == 0)
    verdict = "PASS" if pass_rule else "FAIL"

    return {
        "row": 26,
        "gate": "references_acknowledgments_integrity",
        "context": "LIVE",
        "tier": "Informational",
        "timestamp_utc": datetime.datetime.utcnow().isoformat(timespec="seconds") + "Z",
        "verdict": verdict,
        "blocking": False,
        "has_bibliography": has_bibliography,
        "has_acknowledgments": has_ack,
        "has_copyright": has_copyright,
        "n_placeholders": n_placeholders,
        "placeholder_hits": placeholder_hits,
        "notes": "Row 26 checks bibliography, acknowledgments, copyright, and obvious placeholders."
    }


if __name__ == "__main__":
    here = os.path.dirname(__file__)
    project_root = os.path.abspath(os.path.join(here, ".."))
    out_dir = os.path.join(project_root, "results", "row26_refs")
    os.makedirs(out_dir, exist_ok=True)

    res = gate_row26_refs(project_root)

    with open(os.path.join(out_dir, "result.json"), "w", encoding="utf-8") as f:
        json.dump(res, f, indent=2, sort_keys=True)

    print(res["verdict"])