"""Simple REPL for interactive Agent Johnny 5 chat."""

from __future__ import annotations

import asyncio
import sys
from typing import Any

from easyclaw_tui import __version__
from easyclaw_tui.agent.config import AgentConfig
from easyclaw_tui.agent.core import ForemanAgent
from easyclaw_tui.agent.tools import mcp as mcp_tools

# ANSI codes
BOLD = "\033[1m"
CYAN = "\033[36m"
YELLOW = "\033[33m"
GREEN = "\033[32m"
RED = "\033[31m"
DIM = "\033[2m"
RESET = "\033[0m"
AMBER = "\033[38;5;214m"

_ver = __version__
_ver_line = f"Agent Johnny 5  v{_ver}".center(47)
_tagline = "Your AI Admin for OpenClaw".center(47)

BANNER = f"""\
{AMBER}{BOLD}
 ╔═════════════════════════════════════════════════╗
 ║{_ver_line}║
 ║{_tagline}║
 ╚═════════════════════════════════════════════════╝{RESET}

{DIM} I can run commands, edit configs, query the
 knowledge base, and fix issues on your OpenClaw server.

 Commands:  /reset   — clear conversation history
            /status  — show agent & daemon status
            /help    — show this help
            exit     — quit{RESET}
"""


async def _interactive_confirm(question: str) -> str:
    """Prompt the user for y/n confirmation in the terminal."""
    print(f"\n{YELLOW}{BOLD}Agent Johnny 5 wants to:{RESET}")
    print(f"  {question}")
    print()

    try:
        answer = input(f"{CYAN}Approve? [y/N] > {RESET}").strip().lower()
    except (EOFError, KeyboardInterrupt):
        print()
        return "denied"

    if answer in ("y", "yes"):
        print(f"  {GREEN}Approved{RESET}\n")
        return "approved"
    else:
        print(f"  {RED}Denied{RESET}\n")
        return "denied"


async def _tool_call_handler(name: str, args: dict[str, Any], result: str) -> None:
    """Print tool calls inline so the user can see what the agent is doing."""
    if name == "ask_user":
        # The confirm callback already handled display — don't double-print
        return
    elif name == "run_command":
        cmd = args.get("command", "")
        print(f"  {DIM}$ {cmd}{RESET}")
    elif name == "read_file":
        print(f"  {DIM}reading {args.get('path', '?')}{RESET}")
    elif name == "write_file":
        print(f"  {DIM}writing {args.get('path', '?')}{RESET}")
    elif name == "edit_file":
        print(f"  {DIM}editing {args.get('path', '?')}{RESET}")
    elif name.startswith("mcp_"):
        short = name.replace("mcp_", "")
        print(f"  {DIM}[mcp] {short}{RESET}")
    else:
        print(f"  {DIM}[tool] {name}{RESET}")


def _show_status(config: AgentConfig) -> None:
    """Show daemon status from config file."""
    from easyclaw_tui.agent.config import PID_PATH
    import os

    print(f"\n{AMBER}{BOLD}Agent Status{RESET}")
    print(f"  Model:     {config.model}")
    print(f"  MCP tools: {'enabled' if config.api_key else 'disabled (no API key)'}")
    print(f"  OR key:    {'set' if config.openrouter_key else 'not set'}")

    # Daemon status
    if PID_PATH.exists():
        pid = int(PID_PATH.read_text().strip())
        try:
            os.kill(pid, 0)
            print(f"  Daemon:    {GREEN}running{RESET} (PID {pid})")
        except ProcessLookupError:
            print(f"  Daemon:    {RED}stale PID{RESET} ({pid})")
    else:
        print(f"  Daemon:    {DIM}not running{RESET}")

    if config.last_health_check:
        print(f"  Last check: {config.last_health_check}")

    recent = config.recent_actions[-3:]
    if recent:
        print(f"\n  {BOLD}Recent actions:{RESET}")
        for action in recent:
            t = action.get("time", "?")[:19]
            check = action.get("check", "?")
            print(f"    {DIM}{t}{RESET} — {check}")

    print()


async def run_repl(config: AgentConfig) -> None:
    """Run the interactive REPL."""
    # If stdin is not a TTY (e.g. piped from curl|bash), reopen from /dev/tty
    if not sys.stdin.isatty():
        try:
            sys.stdin = open("/dev/tty", "r")
        except OSError:
            print(f"{RED}Error: No terminal available for interactive input.{RESET}")
            print(f"{DIM}Run 'easyclaw' directly to start Agent Johnny 5.{RESET}")
            return

    # Init MCP if we have a key
    if config.api_key:
        mcp_tools.init_mcp(config.api_key)
    else:
        print(f"{YELLOW}Warning: No EasyClaw API key — MCP tools disabled.{RESET}")
        print(f"{DIM}Set via: export EASYCLAW_API_KEY=ec_live_...{RESET}\n")

    if not config.openrouter_key:
        print(f"{RED}Error: No OpenRouter API key configured.{RESET}")
        print(f"{DIM}Set via: export EASYCLAW_OPENROUTER_KEY=sk-or-...{RESET}")
        print(f"{DIM}  or: easyclaw --openrouter-key sk-or-...{RESET}\n")
        return

    # Set up user confirmation for interactive mode
    from easyclaw_tui.agent.tools.confirm import set_confirm_callback
    set_confirm_callback(_interactive_confirm)

    agent = ForemanAgent(config)
    agent.on_tool_call = _tool_call_handler

    # Try rich for markdown rendering
    try:
        from rich.console import Console
        from rich.markdown import Markdown

        console = Console()
        use_rich = True
    except ImportError:
        console = None  # type: ignore[assignment]
        use_rich = False

    print(BANNER)

    while True:
        try:
            user_input = input(f"{CYAN}{BOLD}You > {RESET}").strip()
        except (EOFError, KeyboardInterrupt):
            print(f"\n{DIM}Goodbye!{RESET}")
            break

        if not user_input:
            continue

        # REPL commands
        low = user_input.lower()
        if low in ("exit", "quit", "/quit"):
            print(f"{DIM}Goodbye!{RESET}")
            break
        elif low == "/reset":
            agent.reset()
            print(f"{GREEN}Conversation cleared.{RESET}\n")
            continue
        elif low == "/status":
            _show_status(config)
            continue
        elif low == "/help":
            print(BANNER)
            continue

        # Send to agent
        print(f"{DIM}Thinking...{RESET}")
        try:
            response = await agent.chat(user_input)
            print()
            if use_rich and console:
                console.print(f"{AMBER}{BOLD}Johnny 5 >{RESET}")
                console.print(Markdown(response))
            else:
                print(f"{AMBER}{BOLD}Johnny 5 >{RESET} {response}")
            print()
        except Exception as e:
            print(f"{RED}Error: {e}{RESET}\n")
