from __future__ import annotations

import os
from typing import Any
from temporalio import activity

from ops_agent.graph import run_ops_graph

@activity.defn
async def run_ops_diagnose_activity(params: dict[str, Any]) -> dict[str, Any]:
    """Runs status check, log fetch, and LLM diagnosis."""
    target_type = params["target_type"]
    target_id = params["target_id"]
    
    # We do NOT run remediation yet, just diagnosis and proposed action
    state = await run_ops_graph(
        target_type=target_type,
        target_id=target_id,
        is_approved=False
    )
    
    return {
        "target_type": state["target_type"],
        "target_id": state["target_id"],
        "status_info": state["status_info"],
        "logs": state["logs"],
        "diagnosis": state["diagnosis"],
        "proposed_action": state["proposed_action"],
        "proposed_action_details": state["proposed_action_details"]
    }

@activity.defn
async def run_ops_remediate_activity(params: dict[str, Any]) -> dict[str, Any]:
    """Runs remediation action once approved."""
    target_type = params["target_type"]
    target_id = params["target_id"]
    proposed_action = params["proposed_action"]
    
    from ops_agent.graph import build_graph_builder
    builder = build_graph_builder()
    graph = builder.compile()
    
    # Run the graph directly starting with the execute node by feeding the state
    state = await graph.ainvoke({
        "target_type": target_type,
        "target_id": target_id,
        "status_info": params.get("status_info", ""),
        "logs": params.get("logs", ""),
        "diagnosis": params.get("diagnosis", ""),
        "proposed_action": proposed_action,
        "proposed_action_details": params.get("proposed_action_details", ""),
        "is_approved": True,
        "action_result": ""
    })
    
    return {
        "action_result": state["action_result"]
    }
