"""Entry point for `python -m easyclaw_installer`."""

import argparse
import os
import sys


def _ensure_tty_stdin() -> None:
    """Ensure stdin is a real terminal for Textual's raw mode.

    When launched via 'curl | bash', stdin is the exhausted pipe from
    curl — NOT a terminal. Textual needs a real tty on fd 0 to enter
    raw mode (termios) and capture individual keystrokes. Without this,
    keystrokes echo as raw text instead of being captured by on_key().

    This is a safety net — install.sh also does '< /dev/tty', but this
    catches cases where the user runs 'python -m easyclaw_installer'
    with a piped stdin.
    """
    if sys.stdin.isatty():
        return  # Already a terminal — nothing to do

    try:
        tty_fd = os.open("/dev/tty", os.O_RDWR)
        os.dup2(tty_fd, 0)  # Replace fd 0 (stdin) with /dev/tty
        os.close(tty_fd)
        sys.stdin = os.fdopen(0, "r")
    except OSError:
        pass  # No controlling terminal (e.g., running in a container)


def main() -> None:
    _ensure_tty_stdin()

    from .app import EasyClawApp
    from .constants import DEFAULT_MCP_URL

    parser = argparse.ArgumentParser(
        description="EasyClaw Agentic Installer"
    )
    parser.add_argument(
        "--api-key",
        default="",
        help="OpenRouter API key for Agent Johnny 5 (or set OPENROUTER_API_KEY env var)",
    )
    parser.add_argument(
        "--mcp-url",
        default=DEFAULT_MCP_URL,
        help=f"MCP knowledge base server URL (default: {DEFAULT_MCP_URL})",
    )
    parser.add_argument(
        "--mcp-key",
        default="",
        help="MCP API key for knowledge base auth (or set EASYCLAW_MCP_KEY env var)",
    )
    parser.add_argument(
        "--no-mcp",
        action="store_true",
        help="Disable MCP knowledge base connection",
    )
    args = parser.parse_args()

    mcp_url = "" if args.no_mcp else args.mcp_url
    mcp_key = "" if args.no_mcp else args.mcp_key
    app = EasyClawApp(api_key=args.api_key, mcp_url=mcp_url, mcp_key=mcp_key)
    app.run()


if __name__ == "__main__":
    main()
