# guardianhub_sdk/agents/specialist_base.py

import uuid
from typing import Dict, Any, List, Optional
from fastapi import APIRouter, HTTPException

from guardianhub.config.settings import settings
from guardianhub.workflows.constants import get_all_activities
from guardianhub.models.agent_models import AgentSubMission
from guardianhub.models.template.agent_plan import MacroPlan
from guardianhub.services.memory_manager import MemoryManager
from guardianhub.services.episodic_manager import EpisodicManager
from guardianhub.clients.a2a_client import A2AClient

class SovereignSpecialistBase:
    """
    The Foundation for all Specialist Agents.
    Encapsulates Planning, Execution, and Context Management.
    """

    def __init__(
            self,
            activities_instance: Any,
            llm_service: Any,
            vector_client: Any,
            graph_client: Any,
            registry_client: Any,
            temporal_client: Optional[Any] = None
    ):
        # 1. Identity & Config
        self.spec = settings.specialist_settings
        self.name = self.spec.agent_name

        # 2. Intelligence Modules
        self.memory = MemoryManager(vector_client, graph_client, registry_client)
        self.episodes = EpisodicManager(vector_client, graph_client, registry_client)
        self.a2a = A2AClient(sender_name=self.name, consul_service=registry_client)
        self.llm = llm_service
        self.temporal_client = temporal_client

        # 3. Domain Activity Instance (The "Fuel")
        self.activities_instance = activities_instance

        # 4. API Gateway
        self.router = APIRouter(prefix="/v1/mission")
        self._setup_routes()

    def get_activities(self) -> list:
        """
        Discovery Hook: Aggregates domain tools for the Temporal Worker.
        Used by the MuscleFactory during ignition.
        """
        return get_all_activities(self.activities_instance)

    def _setup_routes(self):
        @self.router.post("/propose", summary="Tactical Planning Handshake")
        async def propose(mission: AgentSubMission):
            context = await self.memory.get_reasoning_context(
                query=mission.sub_objective,
                template_id=mission.metadata.get("template_id", "TPL-GENERIC"),
                tools=self.spec.capabilities
            )
            plan = await self.llm.generate_specialist_plan(mission, context)
            return {"plan": plan, "rationale": "Audit based on local domain schema."}

        @self.router.post("/execute", summary="Durable Mission Launch")
        async def execute(plan: MacroPlan):
            if not self.temporal_client:
                raise HTTPException(status_code=500, detail="Temporal Muscle not initialized.")

            workflow_id = f"mission-{plan.session_id}-{uuid.uuid4().hex[:6]}"
            await self.temporal_client.start_workflow(
                "SovereignMissionWorkflow",
                args=[plan.model_dump()],
                id=workflow_id,
                task_queue=settings.temporal_settings.task_queue
            )
            return {"status": "running", "workflow_id": workflow_id}