"""CLI for Personal Assistant MCP — setup command."""

import getpass
import sys

import httpx

from personal_assistant_mcp.config import (
    API_URL,
    GOOGLE_CLIENT_ID,
    save_credentials_email,
    save_credentials_google,
)


def _setup_email() -> None:
    """Setup with email/password."""
    email = input("Email: ").strip()
    if not email:
        print("Error: email is required.")
        sys.exit(1)

    password = getpass.getpass("Password: ")
    if not password:
        print("Error: password is required.")
        sys.exit(1)

    print("\nValidating credentials...")
    try:
        resp = httpx.post(
            f"{API_URL}/api/auth/login",
            json={"email": email, "password": password},
        )
        resp.raise_for_status()
    except httpx.ConnectError:
        print("Error: could not connect to the server.")
        sys.exit(1)
    except httpx.HTTPStatusError as e:
        if e.response.status_code == 401:
            print("Error: invalid email or password.")
        else:
            print(f"Error: API returned status {e.response.status_code}")
        sys.exit(1)

    save_credentials_email(email, password)
    print("Credentials saved. You can now use the MCP server.")


def _setup_google() -> None:
    """Setup with Google OAuth."""
    from personal_assistant_mcp.google_auth import google_oauth_flow

    try:
        google_token = google_oauth_flow()
    except RuntimeError as e:
        print(f"Error: {e}")
        sys.exit(1)

    # Exchange Google token for backend JWT tokens
    print("Authenticating with the server...")
    try:
        resp = httpx.post(
            f"{API_URL}/api/auth/google",
            json={"id_token": google_token},
        )
        resp.raise_for_status()
    except httpx.ConnectError:
        print("Error: could not connect to the server.")
        sys.exit(1)
    except httpx.HTTPStatusError as e:
        if e.response.status_code == 401:
            print("Error: Google authentication failed.")
        else:
            print(f"Error: API returned status {e.response.status_code}")
        sys.exit(1)

    data = resp.json()
    save_credentials_google(data["access_token"], data["refresh_token"])
    print("Credentials saved. You can now use the MCP server.")


def setup() -> None:
    """Interactive setup: choose auth method, validate, and save."""
    print("Personal Assistant MCP — Setup\n")

    has_google = bool(GOOGLE_CLIENT_ID)

    if has_google:
        print("How would you like to log in?")
        print("  1. Email and password")
        print("  2. Google account")
        choice = input("\nChoice [1]: ").strip()
        if choice == "2":
            _setup_google()
            return

    _setup_email()


def main() -> None:
    """CLI entrypoint."""
    if len(sys.argv) > 1 and sys.argv[1] == "setup":
        setup()
    else:
        # Default: run the MCP server
        from personal_assistant_mcp.server import mcp

        mcp.run()


if __name__ == "__main__":
    main()
