#!/usr/bin/env python3
# Copyright (c) 2026 PULSE Contributors. Proprietary. All rights reserved.
"""Agent registration, tier detection, and boot briefing cache.

Extracted from pulse_boot.py for Law 7 SoC (files <= 300 lines).
"""
from pulse.core.brain_utils import (
    load_json_dict, save_json,
    AGENT_REGISTRY_FILE, now_iso as _now_iso,
)

# Populated by boot_tasks at import time — imported here for register_agent
try:
    from pulse.brain.boot.tasks import _AGENT_MAP
except Exception:
    _AGENT_MAP: dict = {}

# Boot briefing cache — reuse for 5 minutes across multi-agent boots
_BOOT_CACHE: dict = {"briefing": None, "timestamp": 0.0}
_BOOT_CACHE_TTL = 300  # 5 minutes


def auto_detect_tier(model_name: str) -> str:
    """Auto-detect tier from model name using substring matching."""
    name = model_name.lower()
    premium = ['opus', 'o3', 'gpt-5', 'gpt-4', 'gemini-3-pro', 'gemini-2.5-pro',
               'grok-4', 'llama3.3:70b', 'codex-5']
    for p in premium:
        if p in name:
            return "premium"
    standard = ['sonnet', 'gpt-4o', 'o4-mini', 'gemini-2.5-flash',
                'deepseek-r1', 'qwen2.5:32b', 'mistral-large']
    for s in standard:
        if s in name:
            return "standard"
    fast = ['haiku', 'flash-lite', 'gpt-4o-mini', 'codex-mini', 'gemini-3-flash',
            'gemini-2.5-flash-lite', 'mistral-small', 'phi3', 'mistral:7b']
    for f in fast:
        if f in name:
            return "fast"
    return "standard"


def register_agent(agent_name: str, tier: str) -> dict:
    """Register or update agent in the registry."""
    mapped = _AGENT_MAP.get(agent_name.lower())
    if mapped:
        agent_id = mapped
        agent_type = "agent"
    else:
        agent_id = f"{agent_name.lower()}_daemon"
        agent_type = "daemon"
    registry = load_json_dict(AGENT_REGISTRY_FILE)
    now = _now_iso()

    if agent_id not in registry:
        registry[agent_id] = {
            "agent_id": agent_id, "model": agent_name, "tier": tier,
            "type": agent_type, "status": "booting", "capabilities": [],
            "last_heartbeat": now, "current_task": None,
            "history": {"tasks_completed": 0, "domains": {}},
        }
    else:
        registry[agent_id]["last_heartbeat"] = now
        registry[agent_id]["status"] = "booting"
        registry[agent_id]["tier"] = tier
        if "type" not in registry[agent_id]:
            registry[agent_id]["type"] = agent_type

    save_json(AGENT_REGISTRY_FILE, registry)
    return registry[agent_id]


def get_boot_briefing_cached(agent: str, tier: str, do_claim: bool = False,
                              task_query: str = "") -> str:
    """Return cached boot briefing if fresh (<5min), else regenerate and cache.

    Reduces redundant brain loads when multiple agents boot in the same window.
    Cache is invalidated per (tier, task_query) combination to avoid stale injection.
    """
    import time
    cache_key = f"{tier}:{task_query}"
    cached = _BOOT_CACHE.get("briefing")
    cached_key = _BOOT_CACHE.get("cache_key", "")
    cached_ts = _BOOT_CACHE.get("timestamp", 0.0)
    if cached and cached_key == cache_key and (time.time() - cached_ts) < _BOOT_CACHE_TTL:
        return cached
    from pulse.brain.pulse_boot import boot
    result = boot(agent, tier, do_claim=do_claim, task_query=task_query)
    _BOOT_CACHE["briefing"] = result
    _BOOT_CACHE["timestamp"] = time.time()
    _BOOT_CACHE["cache_key"] = cache_key
    return result
