"""Simple chat CLI that runs a pydantic-ai agent until it returns a structured result."""

from pathlib import Path
from typing import Any

from pydantic_ai import Agent

from .export import export, get_note_str


def cli(agent: Agent[None, Any], vault: Path, hot_start: str | None = None) -> None:
    """Simple chat CLI; exits when the agent returns a non-str (structured result).

    Args:
        agent: The agent to run.
        vault: The vault to use.
        hot_start: The hot start message to use.
    """
    print("\n> Agent: What do you want to generate?")

    message_history: list[Any] = []
    while True:
        if not hot_start:
            user_message = input("\n> You: ").strip()

        else:
            user_message = hot_start
            hot_start = None

        if not user_message:
            continue

        result = agent.run_sync(user_message, message_history=message_history)
        output = result.output
        if isinstance(output, str):
            print(f"\n> Agent: {output}")
            message_history = result.all_messages()

        else:
            print("\n> Agent: ")
            if isinstance(output, list):
                for note in output:
                    print(f"\n== {note.name} ==\n" + get_note_str(note))
            else:
                print(f"\n== {output.name} ==\n" + get_note_str(output))

            user_confirmation = input(
                "\n> Are you okay with this output? (y for yes, or describe what you would like to change): "
            ).strip()

            if user_confirmation == "y":
                export(vault, output)
            else:
                hot_start = user_confirmation
