#!/usr/bin/env python3
"""Matrix-driven agent scheduler — daily handoff chains with correlation_id."""
from __future__ import annotations

import json
import sys
import urllib.request
import uuid
from datetime import datetime, timezone

COCKPIT_URL = "http://127.0.0.1:8600"
TOOLS_URL = "http://127.0.0.1:8700"


def _post(url: str, payload: dict | None = None, timeout: int = 120) -> dict:
    data = json.dumps(payload or {}).encode("utf-8")
    req = urllib.request.Request(
        url,
        data=data,
        headers={"Content-Type": "application/json"},
        method="POST",
    )
    with urllib.request.urlopen(req, timeout=timeout) as resp:
        return json.loads(resp.read().decode("utf-8"))


def _handoff(from_agent: str, to_agent: str, handoff_type: str, payload: dict, cid: str) -> None:
    try:
        _post(
            f"{COCKPIT_URL}/api/agents/handoff",
            {
                "from_agent": from_agent,
                "to_agent": to_agent,
                "handoff_type": handoff_type,
                "payload": payload,
                "correlation_id": cid,
            },
        )
        print(f"handoff {from_agent} -> {to_agent} ({handoff_type})")
    except Exception as exc:
        print(f"handoff failed {from_agent}->{to_agent}: {exc}", file=sys.stderr)


def _trigger_tools(path: str, label: str) -> dict:
    try:
        return _post(f"{TOOLS_URL}{path}", timeout=180)
    except Exception as exc:
        print(f"{label} failed: {exc}", file=sys.stderr)
        return {"ok": False, "error": str(exc)}


def run_chain_0600(cid: str) -> None:
    research = _trigger_tools("/research/run", "research")
    _handoff("browser", "research", "scrape", {"step": "morning_research"}, cid)
    _handoff("research", "marketing", "intel", {"research_ok": research.get("ok", False)}, cid)
    rss = _trigger_tools("/retail/rss/refresh", "rss")
    _handoff("marketing", "retail", "trends", {"rss_ok": rss.get("ok", True), "items": rss.get("count", 0)}, cid)


def run_chain_0630(cid: str) -> None:
    _handoff("sourcing", "product", "suppliers", {"step": "morning_sourcing"}, cid)
    _handoff("product", "halal", "compliance", {"step": "ingredient_check"}, cid)


def run_chain_0700(cid: str) -> None:
    _handoff("sysops", "knowledge", "logs", {"step": "infra_archive"}, cid)
    _handoff("hr", "sysops", "onboarding", {"step": "hr_check", "note": "placeholder check-in"}, cid)
    _handoff("sysops", "herman", "infra_status", {"step": "daily_ops"}, cid)


def run_chain_0800(cid: str) -> None:
    _handoff("email", "bizdev", "leads", {"step": "morning_leads_digest"}, cid)
    _handoff("retail", "bizdev", "opportunities", {"step": "top_opportunities"}, cid)
    _handoff("bizdev", "finance", "valuation", {"step": "pipeline_margin"}, cid)


def main() -> int:
    today = datetime.now(timezone.utc).strftime("%Y-%m-%d")
    base_cid = str(uuid.uuid4())
    print(f"agent_scheduler start {today} correlation={base_cid}")

    run_chain_0600(base_cid)
    run_chain_0630(str(uuid.uuid4()))
    run_chain_0700(str(uuid.uuid4()))
    run_chain_0800(str(uuid.uuid4()))

    try:
        _post(f"{COCKPIT_URL}/api/herman/briefing", timeout=300)
        print("briefing triggered")
    except Exception as exc:
        print(f"briefing skip: {exc}", file=sys.stderr)

    print("agent_scheduler done")
    return 0


if __name__ == "__main__":
    raise SystemExit(main())
