import os
import time
import numpy as np
from pathlib import Path

ENV_FILE = Path(__file__).parent / ".env"
if ENV_FILE.exists():
    with open(ENV_FILE) as f:
        for line in f:
            line = line.strip()
            if line and "=" in line and not line.startswith("#"):
                key, val = line.split("=", 1)
                os.environ.setdefault(key, val)

from core.salience import SalienceEngine
from core.blackboard import Blackboard
from core.scheduler import Scheduler
from core.model_pool import GateType, SLOT_SUMMARY
from agents.router import Router
from agents.tlp import TLPGateLoop
from verifiers.consensus import Verifier


def main(demo_steps: int = 3):
    print("=== SAL-v4 Agent OS Harness ===")
    print(SLOT_SUMMARY)

    bb = Blackboard()
    engine = SalienceEngine()
    gov = Scheduler(bb, engine)
    router = Router(bb, gov)
    loop = TLPGateLoop(bb)

    verifier_duplex = Verifier(["duplex_d1", "duplex_d2"])
    verifier_consensus = Verifier(
        ["verifier_v1", "verifier_v2", "verifier_v3", "verifier_v4"]
    )

    bb.write("objective", "Implement a salience-maximized control loop.", "USER")

    step_count = 0
    try:
        while not gov.halted and step_count < demo_steps:
            if not gov.check_constraints():
                break

            loop.step()

            current_input = "Next step in plan"
            tier = router.triage(current_input)
            model = router.get_model(tier)
            print(f"[*] ROUTER: Selected {tier} ({model})")

            step_telemetry = {
                "delta_a": 0.8,
                "r": 0.2,
                "m": 0.5,
                "c": 0.9,
                "phi": 0.1,
                "t": time.time() - bb.read("metrics")["start_time"],
                "state_vec": np.array([0.1, 0.2]),
            }

            s_prime = engine.calculate_l_sal(
                step_telemetry["delta_a"],
                step_telemetry["r"],
                step_telemetry["m"],
                step_telemetry["c"],
                step_telemetry["phi"],
                step_telemetry["t"],
            )
            bb.write("current_salience", s_prime, "S_ENGINE")
            bb.update_metrics(100, 0.05)
            bb.increment_step()

            action = {
                "type": "tool_call",
                "tool": "write",
                "args": {"path": "file.py"},
                "provenance": "HYBRID",
            }

            gate_decision = verifier_duplex.verify_duplex(
                action, "context", GateType.TOOL_CALL
            )
            if gate_decision.allowed:
                print(f"    [OK] Gate={gate_decision.gate.value} Action approved.")
            else:
                print(
                    f"    [REJECT] Gate={gate_decision.gate.value} {gate_decision.verdict.rationale_tags}"
                )

            step_count += 1
            time.sleep(0.1)

    except KeyboardInterrupt:
        gov.stop("USER_INTERRUPT")

    print(f"\n=== Demo Complete ({step_count} steps) ===")


if __name__ == "__main__":
    main()
