#!/usr/bin/env python3
import json
import subprocess
from pathlib import Path
from datetime import datetime, timezone

ROOT = Path("/home/yeff/public_html/devon")
CANON_EXEC = ROOT / "canon" / "execution"
STATE_DIR = CANON_EXEC / "state"

PLANNER = CANON_EXEC / "bin" / "contract_expansion_planner.py"
CATEGORY_BUILDER = CANON_EXEC / "bin" / "category_contract_builder.py"
ITEM_BUILDER = CANON_EXEC / "bin" / "category_item_contract_builder.py"
GENERIC_RESOLVER = CANON_EXEC / "bin" / "generic_category_state_resolver.py"
VALIDATOR = CANON_EXEC / "bin" / "contract_validator.py"
PLAN = STATE_DIR / "contract_expansion_plan.json"
LOOP_REPORT = STATE_DIR / "category_expansion_loop_report.json"

def utc_now():
    return datetime.now(timezone.utc).isoformat()

def read_json(path):
    return json.loads(path.read_text(encoding="utf-8"))

def write_json(path, data):
    path.parent.mkdir(parents=True, exist_ok=True)
    path.write_text(json.dumps(data, ensure_ascii=False, indent=2) + "\n", encoding="utf-8")

def run_step(name, command):
    result = subprocess.run(
        command,
        shell=True,
        cwd=str(ROOT),
        text=True,
        stdout=subprocess.PIPE,
        stderr=subprocess.PIPE,
        timeout=180
    )

    stdout = (result.stdout or "").strip()
    stderr = (result.stderr or "").strip()

    if result.returncode != 0:
      status = "FAIL"
    elif "STATUS=FAIL" in stdout or "_STATUS=FAIL" in stdout or "FINAL_STATUS=FAIL" in stdout:
      status = "FAIL"
    else:
      status = "PASS"

    return {
        "step": name,
        "command": command,
        "exit_code": result.returncode,
        "status": status,
        "stdout_tail": stdout[-6000:],
        "stderr_tail": stderr[-6000:]
    }

def main():
    before_plan = read_json(PLAN) if PLAN.exists() else {}
    before_next = before_plan.get("next_category") or {}

    steps = []

    steps.append(run_step("planner_before", f"python3 {PLANNER}"))

    refreshed_plan = read_json(PLAN)
    target = refreshed_plan.get("next_category") or {}

    if refreshed_plan.get("final_status") != "PASS":
        report = {
            "report_id": "category_expansion_loop_report",
            "version": "v1",
            "generated_at": utc_now(),
            "final_status": "FAIL",
            "blocking_reason": "planner_before_not_pass",
            "steps": steps,
            "target_category": target
        }
        write_json(LOOP_REPORT, report)
        print("CATEGORY_EXPANSION_LOOP_STATUS=FAIL")
        print("BLOCKING_REASON=planner_before_not_pass")
        print("REPORT=", LOOP_REPORT)
        raise SystemExit(0)

    steps.append(run_step("category_contract_builder", f"python3 {CATEGORY_BUILDER}"))
    if steps[-1]["status"] != "PASS":
        final_status = "FAIL"
    else:
        steps.append(run_step("category_item_contract_builder", f"python3 {ITEM_BUILDER}"))
        final_status = steps[-1]["status"]

    if final_status == "PASS":
        steps.append(run_step("generic_category_state_resolver", f"python3 {GENERIC_RESOLVER}"))
        final_status = steps[-1]["status"]

    if final_status == "PASS":
        steps.append(run_step("contract_validator", f"python3 {VALIDATOR}"))
        final_status = steps[-1]["status"]

    if final_status == "PASS":
        steps.append(run_step("planner_after", f"python3 {PLANNER}"))
        final_status = steps[-1]["status"]

    after_plan = read_json(PLAN) if PLAN.exists() else {}
    after_next = after_plan.get("next_category") or {}

    report = {
        "report_id": "category_expansion_loop_report",
        "version": "v1",
        "generated_at": utc_now(),
        "final_status": final_status,
        "expanded_category": {
            "phase_id": target.get("phase_id"),
            "category_id": target.get("category_id"),
            "category_title": target.get("category_title"),
            "source_path": target.get("source_path"),
            "category_contract_path": target.get("category_contract_path")
        },
        "previous_next_category": before_next,
        "new_next_category": after_next,
        "steps": steps,
        "next_required_action": "run_category_expansion_loop_again" if final_status == "PASS" else "fix_category_expansion_loop_failure"
    }

    write_json(LOOP_REPORT, report)

    print("CATEGORY_EXPANSION_LOOP_STATUS=", final_status)
    print("EXPANDED_PHASE_ID=", target.get("phase_id"))
    print("EXPANDED_CATEGORY_ID=", target.get("category_id"))
    print("EXPANDED_CATEGORY_TITLE=", target.get("category_title"))
    print("NEW_NEXT_PHASE_ID=", after_next.get("phase_id"))
    print("NEW_NEXT_CATEGORY_ID=", after_next.get("category_id"))
    print("NEW_NEXT_CATEGORY_TITLE=", after_next.get("category_title"))
    print("REPORT=", LOOP_REPORT)
    print("NEXT_REQUIRED_ACTION=", report["next_required_action"])

if __name__ == "__main__":
    main()
