"""4emet CLI: init, run, refresh."""

from pathlib import Path

import typer

from foremet import __version__
from foremet.cli.prompts_init import run_init_prompts, write_config, write_env_example
from foremet.config.load import load_config
from foremet.generate.prompt import write_generated_prompt
from foremet.generate.run_script import write_generated_run
from foremet.generate.tools import write_generated_tools
from foremet.ingest.openapi import load_openapi_to_model

app = typer.Typer(
    name="foremet",
    help="4emet ADK: Turn any SaaS (OpenAPI) into an AI agent. Run foremet init, then foremet run.",
)


def _version_callback(value: bool) -> None:
    if value:
        typer.echo(f"foremet {__version__}")
        raise typer.Exit()


@app.callback()
def main(
    _: bool = typer.Option(None, "--version", "-v", callback=_version_callback, is_eager=True),
) -> None:
    """4emet ADK CLI."""
    pass


@app.command()
def init() -> None:
    """Run requirements questionnaire, write adk.config.json, and generate agent/."""
    cwd = Path.cwd()
    typer.echo("Answer the following to create adk.config.json and .env.example.")
    config = run_init_prompts(cwd)
    write_config(cwd, config)
    write_env_example(cwd, config.auth_env_var, config.llm_provider)
    typer.echo(f"Wrote {cwd / 'adk.config.json'} and .env.example.")
    typer.echo("Generating agent...")
    try:
        saas_model = load_openapi_to_model(config.get_openapi_source(), config.is_openapi_url())
        output_dir = cwd / config.output_dir
        write_generated_tools(output_dir, saas_model)
        write_generated_prompt(output_dir, saas_model, config.product_name, config.product_description)
        write_generated_run(output_dir)
        typer.echo(f"Generated {output_dir}/ (tools_generated.py, prompt_generated.py, run.py).")
    except Exception as e:
        typer.echo(typer.style(f"Warning: could not generate agent: {e}", fg=typer.colors.YELLOW))
        typer.echo("Run 'foremet refresh' after fixing OpenAPI source.")


@app.command()
def run() -> None:
    """Load config and run the generated agent (interactive chat)."""
    cwd = Path.cwd()
    try:
        from dotenv import load_dotenv
        load_dotenv(cwd / ".env")
    except ImportError:
        pass
    try:
        config = load_config(cwd)
    except FileNotFoundError as e:
        typer.echo(typer.style(str(e), fg=typer.colors.RED))
        raise typer.Exit(1)
    from foremet.agent.runner import run_invoke
    typer.echo(f"Agent for {config.product_name}. Type a message and press Enter (empty to exit).")
    while True:
        try:
            msg = typer.prompt("You", default="", show_default=False)
        except (EOFError, KeyboardInterrupt):
            break
        if not msg.strip():
            break
        result = run_invoke(cwd=cwd, message=msg)
        for m in reversed(result.get("messages", [])):
            if m.__class__.__name__ == "AIMessage":
                typer.echo(m.content)
                break
    typer.echo("Bye.")


@app.command()
def refresh() -> None:
    """Re-ingest OpenAPI and regenerate agent/ from current config."""
    cwd = Path.cwd()
    try:
        config = load_config(cwd)
    except FileNotFoundError as e:
        typer.echo(typer.style(str(e), fg=typer.colors.RED))
        raise typer.Exit(1)
    typer.echo("Re-ingesting OpenAPI and regenerating agent...")
    try:
        saas_model = load_openapi_to_model(config.get_openapi_source(), config.is_openapi_url())
        output_dir = cwd / config.output_dir
        write_generated_tools(output_dir, saas_model)
        write_generated_prompt(output_dir, saas_model, config.product_name, config.product_description)
        write_generated_run(output_dir)
        typer.echo(f"Regenerated {output_dir}/.")
    except Exception as e:
        typer.echo(typer.style(f"Error: {e}", fg=typer.colors.RED))
        raise typer.Exit(1)


if __name__ == "__main__":
    app()
