"""CLI entry point for Claude Gateway."""

import argparse
import os
import shutil
import sys
import textwrap
from pathlib import Path

CONFIG_DIR = Path.home() / ".config" / "claude-gateway"
CONFIG_FILE = CONFIG_DIR / "config.env"

SYSTEMD_GATEWAY_TEMPLATE = """\
[Unit]
Description=Claude Code Telegram Gateway
After=network.target

[Service]
Type=simple
User={user}
ExecStart={claude_gateway_bin} start
Restart=on-failure
RestartSec=10
EnvironmentFile={config_file}

[Install]
WantedBy=multi-user.target
"""

SYSTEMD_DASHBOARD_TEMPLATE = """\
[Unit]
Description=Claude Code Gateway Dashboard
After=network.target

[Service]
Type=simple
User={user}
ExecStart={claude_gateway_bin} dashboard
Restart=on-failure
RestartSec=10
EnvironmentFile={config_file}

[Install]
WantedBy=multi-user.target
"""


def _prompt(question: str, default: str = "") -> str:
    """Prompt the user for input with an optional default value."""
    if default:
        answer = input(f"{question} [{default}]: ").strip()
        return answer if answer else default
    else:
        return input(f"{question}: ").strip()


def _prompt_yn(question: str, default: bool = True) -> bool:
    """Prompt the user for a yes/no answer."""
    hint = "Y/n" if default else "y/N"
    answer = input(f"{question} [{hint}]: ").strip().lower()
    if not answer:
        return default
    return answer in ("y", "yes")


def cmd_setup(args: argparse.Namespace) -> None:
    """Interactive setup wizard."""
    print("\n=== Claude Gateway Setup ===\n")

    existing = CONFIG_FILE.exists()
    if existing:
        print(f"Existing config found at: {CONFIG_FILE}")
        if not _prompt_yn("Reconfigure?", default=False):
            print("Setup cancelled.")
            return
        print()

    # --- Telegram Bot Token ---
    print("Step 1: Telegram Bot Token")
    print("  Create a bot via @BotFather on Telegram and paste the token below.")
    print("  See: https://core.telegram.org/bots#botfather")
    bot_token = ""
    while not bot_token:
        bot_token = _prompt("  Bot token").strip()
        if not bot_token:
            print("  Bot token is required.")
    print()

    # --- Allowed Chat IDs ---
    print("Step 2: Allowed Chat IDs")
    print("  Only these Telegram chat IDs will be able to use the bot.")
    print("  You can leave this empty now and add your ID after starting the bot.")
    print("  (The bot will show your chat ID when you send it a message.)")
    chat_ids_raw = _prompt("  Chat IDs (comma-separated, or leave empty)", default="")
    print()

    # --- Default Project Path ---
    print("Step 3: Default Project Directory")
    print("  The directory Claude will start in for each new session.")
    default_project = _prompt("  Default project path", default=str(Path.home()))
    print()

    # --- Project Search Directories ---
    print("Step 4: Project Search Directories")
    print("  Directories to scan for projects listed in the /project command.")
    print("  Separate multiple paths with commas.")
    search_dirs = _prompt("  Project search dirs", default=str(Path.home()))
    print()

    # --- New Project Directory ---
    print("Step 5: New Project Directory")
    print("  Where the /newproject command will create new project folders.")
    new_project_dir = _prompt("  New project directory", default=str(Path.home()))
    print()

    # --- Dashboard (optional) ---
    print("Step 6: Dashboard (optional, work in progress)")
    configure_dashboard = _prompt_yn("  Configure dashboard settings?", default=False)
    dashboard_host = "0.0.0.0"
    dashboard_port = "3000"
    if configure_dashboard:
        dashboard_host = _prompt("  Dashboard host", default="0.0.0.0")
        dashboard_port = _prompt("  Dashboard port", default="3000")
    print()

    # --- Write config ---
    CONFIG_DIR.mkdir(parents=True, exist_ok=True)

    lines = [
        "# Claude Gateway configuration",
        "# Generated by: claude-gateway setup",
        "",
        f"TELEGRAM_BOT_TOKEN={bot_token}",
        f"ALLOWED_CHAT_IDS={chat_ids_raw}",
        "",
        f"DEFAULT_PROJECT_PATH={default_project}",
        f"PROJECT_SEARCH_DIRS={search_dirs}",
        f"NEW_PROJECT_DIR={new_project_dir}",
        "",
        f"DASHBOARD_HOST={dashboard_host}",
        f"DASHBOARD_PORT={dashboard_port}",
        "",
    ]

    CONFIG_FILE.write_text("\n".join(lines))
    CONFIG_FILE.chmod(0o600)

    print(f"Config saved to: {CONFIG_FILE}")
    print()

    # --- Systemd (optional) ---
    if _prompt_yn("Generate systemd service files?", default=False):
        cmd_systemd(args, silent=True)

    print("\nSetup complete! Run 'claude-gateway start' to launch the bot.")


def cmd_start(args: argparse.Namespace) -> None:
    """Start the Telegram bot."""
    from .gateway import main
    main()


def cmd_dashboard(args: argparse.Namespace) -> None:
    """Start the web dashboard."""
    try:
        import uvicorn
    except ImportError:
        print("Error: uvicorn is not installed. Install it with: pip install uvicorn[standard]")
        sys.exit(1)

    from .dashboard import app
    from .config import DASHBOARD_HOST, DASHBOARD_PORT

    print(f"Starting dashboard on http://{DASHBOARD_HOST}:{DASHBOARD_PORT}")
    uvicorn.run(app, host=DASHBOARD_HOST, port=DASHBOARD_PORT)


def cmd_systemd(args: argparse.Namespace, silent: bool = False) -> None:
    """Generate systemd service files."""
    claude_gateway_bin = shutil.which("claude-gateway") or "claude-gateway"
    user = os.environ.get("USER", os.environ.get("LOGNAME", "youruser"))
    config_file = str(CONFIG_FILE)

    out_dir = Path(getattr(args, "output_dir", None) or ".")

    gateway_service = SYSTEMD_GATEWAY_TEMPLATE.format(
        user=user,
        claude_gateway_bin=claude_gateway_bin,
        config_file=config_file,
    )
    dashboard_service = SYSTEMD_DASHBOARD_TEMPLATE.format(
        user=user,
        claude_gateway_bin=claude_gateway_bin,
        config_file=config_file,
    )

    gateway_path = out_dir / "claude-gateway.service"
    dashboard_path = out_dir / "claude-dashboard.service"

    gateway_path.write_text(gateway_service)
    dashboard_path.write_text(dashboard_service)

    if not silent:
        print(f"Generated: {gateway_path}")
        print(f"Generated: {dashboard_path}")

    print()
    print("To install the services:")
    print(f"  sudo cp {gateway_path} /etc/systemd/system/")
    print(f"  sudo cp {dashboard_path} /etc/systemd/system/")
    print("  sudo systemctl daemon-reload")
    print("  sudo systemctl enable --now claude-gateway")
    print("  sudo systemctl enable --now claude-dashboard  # optional")


def main() -> None:
    """Main CLI entry point."""
    parser = argparse.ArgumentParser(
        prog="claude-gateway",
        description="Telegram gateway for Claude Code CLI.",
        formatter_class=argparse.RawDescriptionHelpFormatter,
        epilog=textwrap.dedent("""\
            Examples:
              claude-gateway setup       Run the interactive setup wizard
              claude-gateway start       Start the Telegram bot
              claude-gateway dashboard   Start the web dashboard (WIP)
              claude-gateway systemd     Generate systemd service files
        """),
    )
    parser.add_argument(
        "--version", action="version", version=f"%(prog)s 0.1.0"
    )

    subparsers = parser.add_subparsers(dest="command", metavar="command")

    # setup
    setup_parser = subparsers.add_parser(
        "setup", help="Run the interactive setup wizard"
    )
    setup_parser.set_defaults(func=cmd_setup)

    # start
    start_parser = subparsers.add_parser("start", help="Start the Telegram bot")
    start_parser.set_defaults(func=cmd_start)

    # dashboard
    dashboard_parser = subparsers.add_parser(
        "dashboard", help="Start the web dashboard (work in progress)"
    )
    dashboard_parser.set_defaults(func=cmd_dashboard)

    # systemd
    systemd_parser = subparsers.add_parser(
        "systemd", help="Generate systemd service files"
    )
    systemd_parser.add_argument(
        "--output-dir",
        default=".",
        metavar="DIR",
        help="Directory to write service files into (default: current directory)",
    )
    systemd_parser.set_defaults(func=cmd_systemd)

    args = parser.parse_args()

    if not args.command:
        parser.print_help()
        sys.exit(0)

    args.func(args)


if __name__ == "__main__":
    main()
