import os

test_f = r"C:\Users\intel\AppData\Local\OptimusRuntime\Labs\AR74\12_ar88_authority_operational_closure\test_isolated_brain_route.py"

with open(test_f, "r", encoding="utf-8") as f:
    content = f.read()

old_poll_loop = """                    if curr_st in ("FAILED", "SUCCESS", "COMPLETED", "BLOCKED"):
                        evidence_res["task_terminal_status"] = curr_st
                        terminal_status_reached = True
                        if evidence_res["shadow_hook_requested"] and evidence_res["shadow_hook_accepted"]:
                            break"""

new_poll_loop = """                    # In AR-88, distinguish true task terminal status (e.g. FAILED, COMPLETED, VERIFIED_SUCCESS)
                    if curr_st in ("FAILED", "SUCCESS", "COMPLETED", "BLOCKED", "VERIFICATION_FAILED", "STALLED", "CAPABILITY_BLOCKER", "INPUT_INVALID"):
                        evidence_res["task_terminal_status"] = curr_st
                        terminal_status_reached = True
                        # Poll until shadow hook has completed its cycle or failed
                        if evidence_res["shadow_hook_completed_or_failed"]:
                            break"""

old_report_check = """        # Check for correlated shadow repair report in reports directory
        reports_dir = os.path.join(CANDIDATE_WS, "reports", "self_repair")
        if os.path.isdir(reports_dir):
            for inc in os.listdir(reports_dir):
                rep_f = os.path.join(reports_dir, inc, "shadow_repair_report.json")
                if os.path.isfile(rep_f):
                    evidence_res["shadow_repair_report_found"] = True
                    break"""

new_report_check = """        # Check for correlated shadow repair report matching correlated_incident_id
        corr_inc = evidence_res.get("correlated_incident_id")
        reports_dir = os.path.join(CANDIDATE_WS, "reports", "self_repair")
        if os.path.isdir(reports_dir) and corr_inc:
            rep_f = os.path.join(reports_dir, corr_inc, "shadow_repair_report.json")
            if os.path.isfile(rep_f):
                evidence_res["shadow_repair_report_found"] = True
                try:
                    with open(rep_f, "r", encoding="utf-8") as rf:
                        rep_data = json.load(rf)
                        evidence_res["shadow_status"] = rep_data.get("shadow_status")
                        evidence_res["candidate_repair"] = rep_data.get("candidate_repair")
                except Exception as _ex_rep:
                    evidence_res["shadow_status_read_error"] = str(_ex_rep)
        elif os.path.isdir(reports_dir):
            # Fallback search if corr_inc was not populated in activity
            for inc in os.listdir(reports_dir):
                rep_f = os.path.join(reports_dir, inc, "shadow_repair_report.json")
                if os.path.isfile(rep_f):
                    evidence_res["shadow_repair_report_found"] = True
                    try:
                        with open(rep_f, "r", encoding="utf-8") as rf:
                            rep_data = json.load(rf)
                            evidence_res["shadow_status"] = rep_data.get("shadow_status")
                            evidence_res["candidate_repair"] = rep_data.get("candidate_repair")
                    except Exception:
                        pass
                    break"""

old_exit = """    if not (res.get("shadow_hook_requested") and res.get("shadow_hook_accepted")):
        sys.exit(1)"""

new_exit = """    # AR-88 Strict Evaluation Contract:
    # 1. Server started and request succeeded (200)
    # 2. task_id exists
    # 3. task_terminal_status is not None and not null
    # 4. Lifecycle transitions: REQUESTED, ACCEPTED, STARTED, and COMPLETED (or FAILED)
    # 5. Correlated incident_id and shadow_run_id exist
    ok_server = res.get("server_started") is True
    ok_code = res.get("request_status_code") == 200
    ok_task = bool(res.get("dispatched_task_id"))
    ok_term = res.get("task_terminal_status") is not None
    ok_hook_req = res.get("shadow_hook_requested") is True
    ok_hook_acc = res.get("shadow_hook_accepted") is True
    ok_hook_start = res.get("shadow_hook_started") is True
    ok_hook_end = res.get("shadow_hook_completed_or_failed") is True
    ok_corr = bool(res.get("correlated_incident_id") and res.get("correlated_shadow_run_id"))

    if not (ok_server and ok_code and ok_task and ok_term and ok_hook_req and ok_hook_acc and ok_hook_start and ok_hook_end and ok_corr):
        print(f"[AR88] OPERATIONAL_E2E=FAIL: Validation criteria not satisfied: ok_term={ok_term}, ok_corr={ok_corr}, ok_hook_end={ok_hook_end}")
        sys.exit(1)
    print("[AR88] OPERATIONAL_E2E=PASS: All operational lifecycle, terminal status, and correlation requirements satisfied.")"""

if old_poll_loop in content and old_report_check in content and old_exit in content:
    content = content.replace(old_poll_loop, new_poll_loop)
    content = content.replace(old_report_check, new_report_check)
    content = content.replace(old_exit, new_exit)
    with open(test_f, "w", encoding="utf-8") as f:
        f.write(content)
    print("SUCCESS: test_isolated_brain_route.py updated with strict operational contract!")
else:
    print("ERROR: blocks not matched in test_isolated_brain_route.py")

