import os
import sys

lab = r"C:\Users\intel\AppData\Local\OptimusRuntime\Labs\AR74\12_ar88_authority_operational_closure"
candidate_ws = os.path.join(lab, "candidate_workspace")

target_file = os.path.join(candidate_ws, "app", "remediation", "self_repair", "live_shadow_hook.py")

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

# Check lines 1805-1825:
old_accepted_call = """        # AR-88 State Transition: Record SHADOW_HOOK_ACCEPTED in task state
        tid = terminal_rec.get("task_id") or snapshot.mission_id
        try:
            default_canonical_task_state_updater({
                "task_id": tid,
                "mission_id": snapshot.mission_id,
                "activity_event": "SHADOW_HOOK_ACCEPTED",
                "message": "Live shadow hook accepted by engine",
            })
        except Exception:
            pass"""

new_accepted_call = """        # AR-88 State Transition: Record SHADOW_HOOK_ACCEPTED in task state
        tid = terminal_rec.get("task_id") or snapshot.mission_id
        effective_updater_pre = (
            task_state_updater_callable
            or get_canonical_task_state_updater(mission_id=snapshot.mission_id, instance_id=snapshot.instance_id)
            or default_canonical_task_state_updater
        )
        try:
            accept_payload = {
                "task_id": tid,
                "mission_id": snapshot.mission_id,
                "activity_event": "SHADOW_HOOK_ACCEPTED",
                "message": "Live shadow hook accepted by engine",
            }
            if "operational_tasks" in terminal_rec:
                accept_payload["operational_tasks"] = terminal_rec["operational_tasks"]
            effective_updater_pre(accept_payload)
        except Exception as _ex_acc:
            logger.debug(f"[LiveShadowHook] Could not record SHADOW_HOOK_ACCEPTED: {_ex_acc}")"""

if old_accepted_call in content:
    content = content.replace(old_accepted_call, new_accepted_call)
    print("Found and replaced old_accepted_call!")
else:
    print("WARNING: old_accepted_call not found!")

# Also check _async_worker in async_dispatch:
old_worker_started = """                    # AR-88 State Transition: SHADOW_HOOK_STARTED
                    try:
                        default_canonical_task_state_updater({
                            "task_id": tid,
                            "mission_id": snapshot.mission_id,
                            "activity_event": "SHADOW_HOOK_STARTED",
                            "message": "Live shadow repair execution started",
                        })
                    except Exception:
                        pass"""

new_worker_started = """                    # AR-88 State Transition: SHADOW_HOOK_STARTED
                    try:
                        started_payload = {
                            "task_id": tid,
                            "mission_id": snapshot.mission_id,
                            "activity_event": "SHADOW_HOOK_STARTED",
                            "message": "Live shadow repair execution started",
                        }
                        if "operational_tasks" in terminal_rec:
                            started_payload["operational_tasks"] = terminal_rec["operational_tasks"]
                        effective_updater(started_payload)
                    except Exception as _ex_st:
                        logger.debug(f"[LiveShadowHook] Could not record SHADOW_HOOK_STARTED: {_ex_st}")"""

if old_worker_started in content:
    content = content.replace(old_worker_started, new_worker_started)
    print("Found and replaced old_worker_started!")
else:
    print("WARNING: old_worker_started not found!")

# Also check completed/failed in _async_worker:
old_worker_completed = """                    # AR-88 State Transition: SHADOW_HOOK_COMPLETED
                    try:
                        default_canonical_task_state_updater({
                            "task_id": tid,
                            "mission_id": snapshot.mission_id,
                            "activity_event": "SHADOW_HOOK_COMPLETED",
                            "status": getattr(rep, "shadow_status", "UNKNOWN"),
                            "incident_id": getattr(rep, "incident_id", None),
                            "shadow_run_id": getattr(rep, "shadow_run_id", None),
                            "message": "Live shadow repair cycle completed",
                        })
                    except Exception:
                        pass"""

new_worker_completed = """                    # AR-88 State Transition: SHADOW_HOOK_COMPLETED
                    try:
                        comp_payload = {
                            "task_id": tid,
                            "mission_id": snapshot.mission_id,
                            "activity_event": "SHADOW_HOOK_COMPLETED",
                            "status": getattr(rep, "shadow_status", "UNKNOWN"),
                            "incident_id": getattr(rep, "incident_id", None),
                            "shadow_run_id": getattr(rep, "shadow_run_id", None),
                            "message": "Live shadow repair cycle completed",
                        }
                        if "operational_tasks" in terminal_rec:
                            comp_payload["operational_tasks"] = terminal_rec["operational_tasks"]
                        effective_updater(comp_payload)
                    except Exception as _ex_comp:
                        logger.debug(f"[LiveShadowHook] Could not record SHADOW_HOOK_COMPLETED: {_ex_comp}")"""

if old_worker_completed in content:
    content = content.replace(old_worker_completed, new_worker_completed)
    print("Found and replaced old_worker_completed!")
else:
    print("WARNING: old_worker_completed not found!")

with open(target_file, "w", encoding="utf-8") as f:
    f.write(content)

print("SUCCESS: live_shadow_hook.py updated with effective_updater propagation!")

