"""
Main integration agent invocation function
"""

import os
from typing import Any, Literal, Optional
from .create_client import create_client
from .configure_graph import configure_graph
from ads4gpts_core.prompts import (
    ADS4GPTS_INTEGRATION_USER_TEMPLATE,
    ADS4GPTS_INTEGRATION_SYSTEM_TEMPLATE,
)
from dotenv import load_dotenv

load_dotenv()


def invoke_integration_agent(
    user_input: str,
    message_history: list[Any],
    thread_id: str,
    session_id: str,
    is_interrupted: Optional[bool] = False,
    owner: Optional[str] = None,
    integration_model_provider: Optional[Literal["OPENAI", "ANTHROPIC"]] = "OPENAI",
    integration_model_name: Optional[
        Literal["gpt-4o", "gpt-4o-mini", "claude-3-opus"]
    ] = "gpt-4o",
    integration_user_prompt: Optional[str] = ADS4GPTS_INTEGRATION_USER_TEMPLATE,
    integration_system_prompt: Optional[str] = ADS4GPTS_INTEGRATION_SYSTEM_TEMPLATE,
    is_first_run: bool = False,
    ads4gpts_agent_url: Optional[str] = None,
    gpt_id: Optional[str] = None,
    ads4gpts_api_key: Optional[str] = None,
    ssp_id: Optional[str] = None,
    graph_recursion_limit: int = 100,
    assistant_id: str = "agent",
):
    """
        Invoke the integration agent graph

        This function creates a LangGraph client, configures the graph, and starts
        a streaming run based on the provided parameters.

        Args:
            user_input: The user's input message
            message_history: Previous conversation messages
            thread_id: Thread ID for the conversation
            session_id: Session identifier
            integration_model_provider: Model provider (OPENAI or ANTHROPIC)
            integration_model_name: Model name to use
            integration_user_prompt: User prompt template
            integration_system_prompt: System prompt
            is_interrupted: Whether this is an interrupted/resumed run
            owner: Owner identifier
            is_first_run: Whether this is the first run (default: False)
            ads4gpts_agent_url: Ads4GPTs Agent API URL (defaults to ADS4GPTS_AGENT_URL env var)
            gpt_id: GPT ID (defaults to ADS4GPTS_GPT_ID env var)
            ads4gpts_api_key: API key (defaults to ADS4GPTS_API_KEY env var)
            ssp_id: SSP ID (defaults to ADS4GPTS_SSP_ID env var)
            graph_recursion_limit: Maximum recursions (default: 100)
            assistant_id: Assistant ID (default: 'agent')

        Returns:
            Stream response from the LangGraph client

        Example:
    ```python
            stream = invoke_integration_agent(
                user_input="Hello!",
                message_history=[],
                thread_id="thread_123",
                session_id="session_123",
                integration_model_provider="OPENAI",
                integration_model_name="gpt-4o",
                integration_user_prompt="User: {input}",
                integration_system_prompt="You are helpful",
                is_interrupted=False,
                owner="user_123",
                is_first_run=True
            )

            async for chunk in stream:
                print(chunk)
    ```
    """
    # Get environment variables with defaults
    api_url = ads4gpts_agent_url or os.getenv("ADS4GPTS_AGENT_URL", "")
    ads4gpts_gpt_id = gpt_id or os.getenv("ADS4GPTS_GPT_ID", "")
    api_key = ads4gpts_api_key or os.getenv("ADS4GPTS_API_KEY", "")
    ads4gpts_ssp_id = ssp_id or os.getenv("ADS4GPTS_SSP_ID", "")

    # Create client
    client = create_client(api_url=api_url)

    # Configure graph
    config = configure_graph(
        session_id=session_id,
        owner=owner,
        gpt_id=ads4gpts_gpt_id,
        ads4gpts_api_key=api_key,
        ssp_id=ads4gpts_ssp_id,
        integration_system_prompt=integration_system_prompt,
        integration_user_prompt=integration_user_prompt,
        integration_model_provider=integration_model_provider,
        integration_model_name=integration_model_name,
        recursion_limit=graph_recursion_limit,
    )

    stream_mode = ["events", "updates", "messages"]

    # Create stream based on state
    if is_interrupted:
        print("Interrupt injection!")
        stream_response = client.runs.stream(
            thread_id=thread_id,
            assistant_id=assistant_id,
            stream_mode=stream_mode,
            config=config,
            on_disconnect="continue",
            command={"resume": user_input},
            stream_subgraphs=True,
        )
    elif is_first_run:
        print("First run")
        stream_response = client.runs.stream(
            thread_id=thread_id,
            assistant_id=assistant_id,
            input={
                "input": user_input,
                "messages": [
                    *message_history,
                    {"role": "human", "content": user_input},
                ],
            },
            stream_mode=stream_mode,
            config=config,
            on_disconnect="continue",
            stream_subgraphs=True,
        )
    else:
        print("Subsequent run")
        stream_response = client.runs.stream(
            thread_id=thread_id,
            assistant_id=assistant_id,
            input={
                "messages": [
                    *message_history,
                    {"role": "human", "content": user_input},
                ],
            },
            stream_mode=stream_mode,
            config=config,
            on_disconnect="continue",
            stream_subgraphs=True,
        )

    return stream_response
