import logging

from dataclasses import dataclass, field
from dotenv import load_dotenv
from livekit import agents
from livekit.agents import AgentSession, Agent, RoomInputOptions
from livekit.plugins import (
    google,
    noise_cancellation,
)
from typing import Literal, Optional, Union

logger = logging.getLogger(__name__)

load_dotenv()

@dataclass
class UserCommand:
    command: str

@dataclass
class AppCommand:
    action: Literal["open", "close"]
    app_name: str

@dataclass
class KeyboardCommand:
    action: Literal["press", "type"]
    keys: Optional[list[str]] = None
    sentence: Optional[str] = None

@dataclass
class ShellCommand:
    command: str

@dataclass
class FormattedCommand:
    category: Literal["app", "shell", "keyboard"]
    details: Union[AppCommand, KeyboardCommand, ShellCommand]


class Assistant(Agent):
    def __init__(self) -> None:
        super().__init__(
            instructions="""
            You are a helpful voice AI assistant. Your task is to take a user's command
            and format it into a structured JSON object. The command will be one of three categories:
            'app', 'shell', or 'keyboard'.

            1.  **app**: For opening or closing applications.
                - `action`: "open" or "close".
                - `app_name`: The name of the application.
                Example: "open chrome" -> {"category": "app", "details": {"action": "open", "app_name": "chrome"}}

            2.  **shell**: For executing shell commands.
                - `command`: The best shell command to execute the user's instruction.
                Example: "list all files in the current directory" -> {"category": "shell", "details": {"command": "ls -la"}}

            3.  **keyboard**: For keyboard actions like pressing key combinations or typing sentences.
                - `action`: "press" or "type".
                - `keys`: A list of keys for key combinations (for "press" action).
                - `sentence`: The sentence to type (for "type" action).
                Example 1: "press control shift escape" -> {"category": "keyboard", "details": {"action": "press", "keys": ["ctrl", "shift", "esc"]}}
                Example 2: "type hello world" -> {"category": "keyboard", "details": {"action": "type", "sentence": "hello world"}}

            You must only respond with the JSON object.
            """
        )

async def entrypoint(ctx: agents.JobContext):  
    # The user command is now accessed from the JobContext
    user_command = UserCommand(command=ctx.input.command)

    session = AgentSession(
        llm=google.LLM(
            model="groq/openai/gpt-4-oss-120b",
            json_mode=True,
        ),
    )  
  
    await session.start(  
        room=ctx.room,  
        agent=Assistant(),  
        room_input_options=RoomInputOptions(  
            noise_cancellation=noise_cancellation.BVC(),  
        ),  
    )  
  
    # The LLM will return a JSON object based on the instructions.
    # We specify FormattedCommand as the return type hint.
    formatted_command: FormattedCommand = await session.generate_reply(
        user_command
    )
    return formatted_command

async def command_formater(command: str):
    # This function will now run the agent and return the structured command.
    # The `run_app` function is for simulation and doesn't take an 'input' argument directly.
    # The input must be provided as a JSON string to stdin, which run_app handles
    # when a second argument is provided.
    import json
    job_input = json.dumps({"command": command})
    opts = agents.WorkerOptions(entrypoint_fnc=entrypoint)
    return await agents.cli.run_app(opts, job_input)