"""Workflow definition for the meeting graph."""

from typing import Literal
from langgraph.graph import StateGraph, START, END
from langgraph.checkpoint.memory import MemorySaver

from .state import MeetingState
from .nodes import (
    node_opening,
    node_status_check,
    node_select_speaker,
    node_speak,
    node_user_input,
    node_issue_resolution,
    node_closing
)

def should_continue_discussion(state: MeetingState) -> Literal["speak", "user_input", "issue_resolution", "closing"]:
    """Decide next step based on selected speaker.

    Routes to:
    - "speak" for AI participants
    - "user_input" for Human participants
    - "issue_resolution" when FINISH received during status_check phase
    - "closing" when FINISH signal received in other phases
    """
    next_speaker = state.get("next_speaker")

    if next_speaker == "FINISH":
        phase = state.get("current_phase", "")
        if phase == "status_check":
            return "issue_resolution"
        return "closing"

    # Check if selected speaker is human
    participants = state.get("participants", [])
    for p in participants:
        if p["name"] == next_speaker and not p.get("is_ai", True):
            return "user_input"

    return "speak"

def create_workflow() -> StateGraph:
    """Create and compile the meeting workflow."""
    
    workflow = StateGraph(MeetingState)
    
    # Add Nodes
    workflow.add_node("opening", node_opening)
    workflow.add_node("status_check", node_status_check)

    # Cyclical Discussion Nodes
    workflow.add_node("select_speaker", node_select_speaker)
    workflow.add_node("speak", node_speak)

    # User Input (Human-in-the-loop)
    workflow.add_node("user_input", node_user_input)

    # Issue Resolution Phase
    workflow.add_node("issue_resolution", node_issue_resolution)

    # Closing
    workflow.add_node("closing", node_closing)
    
    # Define Edges
    # START -> Opening
    workflow.add_edge(START, "opening")
    
    # Opening -> Status Check
    workflow.add_edge("opening", "status_check")
    
    # Status Check -> Start Discussion Cycle (Selector)
    workflow.add_edge("status_check", "select_speaker")
    
    # Discussion Cycle: Selector -> [Conditional] -> Speak/UserInput/IssueResolution/Closing
    workflow.add_conditional_edges(
        "select_speaker",
        should_continue_discussion,
        {
            "speak": "speak",
            "user_input": "user_input",
            "issue_resolution": "issue_resolution",
            "closing": "closing"
        }
    )
    
    # Speak -> Loop back to Selector
    workflow.add_edge("speak", "select_speaker")

    # User Input -> Loop back to Selector
    workflow.add_edge("user_input", "select_speaker")

    # Issue Resolution -> Start issue discussion cycle
    workflow.add_edge("issue_resolution", "select_speaker")

    # Closing -> END
    workflow.add_edge("closing", END)
    
    # Compile with interrupt_before for human-in-the-loop
    checkpointer = MemorySaver()
    app = workflow.compile(
        checkpointer=checkpointer,
        interrupt_before=["user_input"]  # Pause before user input node
    )
    
    return app

