"""Shared runtime bootstrap helpers for CLI and API entrypoints."""

from __future__ import annotations

import logging
from typing import Any

from kiessclaw.core.config import load_and_resolve_config
from kiessclaw.core.memory import MemoryEngine

logger = logging.getLogger("kiessclaw")


def load_config(config_path: str = "config/config.yaml") -> dict[str, Any]:
    """Load validated runtime config from path."""
    return load_and_resolve_config(config_path)


def workspace_memory(config: dict[str, Any]) -> MemoryEngine:
    """Create memory engine for configured workspace root."""
    workspace_root = config.get("workspace", {}).get("root", "./workspace")
    return MemoryEngine(workspace_root)


def build_agent_registry(config: dict[str, Any]) -> dict[str, Any]:
    """Instantiate all enabled SDR+SEO agents from configuration."""
    from kiessclaw.agents.inbox_agent import KiessInboxAgent
    from kiessclaw.agents.metrics_agent import KiessMetricsAgent
    from kiessclaw.agents.pen_agent import KiessPenAgent
    from kiessclaw.agents.prospector_agent import KiessProspectorAgent
    from kiessclaw.agents.sequencer_agent import KiessSequencerAgent
    from kiessclaw.seo.kana_agent import KiessAnalystAgent
    from kiessclaw.seo.krawl_agent import KiessCrawlerAgent
    from kiessclaw.seo.krep_agent import KiessReporterAgent
    from kiessclaw.seo.ksco_agent import KiessScoutAgent
    from kiessclaw.seo.kwri_agent import KiessWriterAgent

    memory = workspace_memory(config)
    registry: dict[str, Any] = {}
    agents_config = config.get("agents", {})

    if agents_config.get("KPRO", {}).get("enabled", True):
        registry["KPRO"] = KiessProspectorAgent(config, memory)
    if agents_config.get("KSEQ", {}).get("enabled", True):
        registry["KSEQ"] = KiessSequencerAgent(config, memory)
    if agents_config.get("KPEN", {}).get("enabled", True):
        registry["KPEN"] = KiessPenAgent(config, memory)
    if agents_config.get("KINB", {}).get("enabled", True):
        registry["KINB"] = KiessInboxAgent(config, memory)
    if agents_config.get("KMET", {}).get("enabled", True):
        registry["KMET"] = KiessMetricsAgent(config, memory)
    if agents_config.get("KRAWL", {}).get("enabled", True):
        registry["KRAWL"] = KiessCrawlerAgent(config, memory)
    if agents_config.get("KANA", {}).get("enabled", True):
        registry["KANA"] = KiessAnalystAgent(config, memory)
    if agents_config.get("KWRI", {}).get("enabled", True):
        registry["KWRI"] = KiessWriterAgent(config, memory)
    if agents_config.get("KSCO", {}).get("enabled", True):
        registry["KSCO"] = KiessScoutAgent(config, memory)
    if agents_config.get("KREP", {}).get("enabled", True):
        registry["KREP"] = KiessReporterAgent(config, memory)

    logger.info("[KIESSCLAW] %s agent(s) loaded: %s", len(registry), list(registry.keys()))
    return registry

