from __future__ import annotations

import argparse
import os
from pathlib import Path

from .agents import DEFAULT_AGENT, get_agent, list_agents
from .chat import (
    APIError,
    DEFAULT_MEMORY_FILE,
    DEFAULT_MODEL,
    DEFAULT_OPENROUTER_API_KEY,
    FreeNeuroChatClient,
)


def _build_parser() -> argparse.ArgumentParser:
    parser = argparse.ArgumentParser(
        prog="revengelibrary",
        description="Interactive terminal chat with free OpenRouter models.",
    )
    parser.add_argument(
        "--api-key",
        default=os.getenv("OPENROUTER_API_KEY", DEFAULT_OPENROUTER_API_KEY),
        help="OpenRouter API key. Fallback: OPENROUTER_API_KEY, then built-in key.",
    )
    parser.add_argument(
        "--model",
        default=DEFAULT_MODEL,
        help="Model name on OpenRouter (default uses a free model).",
    )
    parser.add_argument(
        "--system",
        default=None,
        help="System prompt override. If omitted, selected agent prompt is used.",
    )
    parser.add_argument(
        "--agent",
        default=os.getenv("REVENGELIBRARY_AGENT", DEFAULT_AGENT),
        help="Agent role. Use --list-agents to view available roles.",
    )
    parser.add_argument(
        "--list-agents",
        action="store_true",
        help="Show available agent roles and exit.",
    )
    parser.add_argument(
        "--memory-file",
        default=os.getenv("REVENGELIBRARY_MEMORY_FILE", DEFAULT_MEMORY_FILE),
        help=(
            "JSON file for chat memory. "
            "Fallback: REVENGELIBRARY_MEMORY_FILE, then built-in package memory file."
        ),
    )
    return parser


def main() -> int:
    parser = _build_parser()
    args = parser.parse_args()

    if args.list_agents:
        for profile in list_agents():
            print(f"{profile.name}: {profile.title}")
        return 0

    try:
        agent = get_agent(args.agent)
    except ValueError as exc:
        parser.error(str(exc))

    system_prompt = args.system if args.system else agent.system_prompt
    memory_file = _agent_memory_file(args.memory_file, agent.name)

    client = FreeNeuroChatClient(
        api_key=args.api_key or DEFAULT_OPENROUTER_API_KEY,
        model=args.model,
        system_prompt=system_prompt,
        memory_file=memory_file,
    )

    print(
        "Interactive chat started. "
        "Type 'exit' to quit, 'reset' to clear history, 'forget' to delete memory file."
    )
    while True:
        try:
            text = input("you> ").strip()
        except (EOFError, KeyboardInterrupt):
            print("\nbye")
            return 0

        if not text:
            continue
        if text.lower() in {"exit", "quit"}:
            print("bye")
            return 0
        if text.lower() == "reset":
            client.reset()
            print("history reset")
            continue
        if text.lower() == "forget":
            client.reset()
            client.clear_memory_file()
            print("history reset and memory file deleted")
            continue

        try:
            answer = client.send(text)
            print(f"ai> {answer}")
        except APIError as exc:
            print(f"api error: {exc}")
        except Exception as exc:  # noqa: BLE001
            print(f"unexpected error: {exc}")


def _agent_memory_file(memory_file: str | None, agent_name: str) -> str | None:
    if not memory_file:
        return None
    if agent_name == DEFAULT_AGENT:
        return memory_file

    path = Path(memory_file).expanduser()
    suffix = path.suffix or ".json"
    stem = path.stem if path.suffix else path.name
    return str(path.with_name(f"{stem}__{agent_name}{suffix}"))


if __name__ == "__main__":
    raise SystemExit(main())
