# guardianhub_sdk/workflows/specialist_workflow.py

from typing import Dict, Any
from temporalio import workflow
from .constants import get_activity_options
from guardianhub.config.settings import settings


@workflow.defn(name="SovereignMissionWorkflow")
class SovereignMissionWorkflow:
    """
    SDK-provided dynamic orchestration engine.
    Sources activity names directly from the JSON configuration.
    """

    @workflow.run
    async def run(self, plan: Dict[str, Any]) -> Dict[str, Any]:
        mapping = settings.workflow_settings.activity_mapping
        session_id = plan.get("session_id")

        # 1. SENSORY INJECTION
        # Lookup the mapped method name for the 'facts' constant
        facts_activity = mapping.get("get_graph_facts_activity")
        ground_truth = await workflow.execute_activity(
            facts_activity,
            args=[plan.get("instruction", "")],
            **get_activity_options(facts_activity)
        )

        # 2. ReAct LOOP
        invoke_tool_activity = mapping.get("invoke_semantic_tool_activity")
        results = {}
        for step in plan.get("steps", []):
            res = await workflow.execute_activity(
                invoke_tool_activity,
                args=[step, ground_truth],
                **get_activity_options(invoke_tool_activity)
            )
            results[step.get("step_id")] = res

        # 3. SYNTHESIS & CALLBACK
        report_activity = mapping.get("generate_final_report_activity")
        callback_activity = mapping.get("notify_orchestrator_callback_activity")

        report = await workflow.execute_activity(
            report_activity, args=[results], **get_activity_options(report_activity)
        )

        await workflow.execute_activity(
            callback_activity,
            args=[{"session_id": session_id, "payload": report}],
            **get_activity_options(callback_activity)
        )

        return {"status": "SUCCESS", "session_id": session_id}