#!/usr/bin/env python3
"""
Optional CLI for setup & authentication.

The preferred way is to let Claude handle setup via MCP tools:
  - setup_google_workspace (saves config)
  - authenticate_account (triggers OAuth)

This CLI exists as a fallback for manual setup.

Usage:
    gw-mcp-auth                     # interactive setup + auth
    gw-mcp-auth --profile business  # auth one profile
    gw-mcp-auth --status            # show setup status
"""

import argparse
import json
import sys

from .oauth import (
    CONFIG_FILE,
    authenticate_profile_async,
    create_config,
    get_setup_status,
    list_profiles,
    _ensure_dirs,
)


def _ask(prompt: str) -> str:
    return input(prompt).strip()


def init_config() -> None:
    _ensure_dirs()
    print("\n  Google Workspace MCP — Setup\n")
    print("You need a Google Cloud OAuth 2.0 Client ID (Desktop app).")
    print("Get one at: https://console.cloud.google.com/apis/credentials\n")

    client_id = _ask("Client ID: ")
    client_secret = _ask("Client Secret: ")

    profiles = []
    while True:
        print(f"\n--- Account #{len(profiles) + 1} ---")
        name = _ask("Profile name (e.g. business, personal): ")
        email = _ask("Gmail address: ")
        description = _ask("Description (optional): ")
        profiles.append({"name": name, "email": email, "description": description})
        more = _ask("Add another? (y/n): ")
        if more.lower() != "y":
            break

    result = create_config(client_id, client_secret, profiles)
    print(f"\n  Config saved to {result['config_path']}")
    print(f"  Profiles: {', '.join(result['profiles'])}\n")


def main() -> None:
    parser = argparse.ArgumentParser(description="Google Workspace MCP — Auth")
    parser.add_argument("--status", action="store_true", help="Show setup status")
    parser.add_argument("--init", action="store_true", help="Create config interactively")
    parser.add_argument("--profile", type=str, help="Authenticate one profile")
    parser.add_argument("--force", action="store_true", help="Re-authenticate all")
    args = parser.parse_args()

    if args.status:
        import pprint
        pprint.pprint(get_setup_status())
        return

    if args.init or not CONFIG_FILE.exists():
        init_config()

    if args.profile:
        import asyncio
        result = asyncio.run(authenticate_profile_async(args.profile))
        print(f"\n  {result.get('message', result)}")
    else:
        profiles = list_profiles()
        if not profiles:
            print("No profiles configured. Run with --init first.")
            return
        print(f"\nAuthenticating {len(profiles)} profile(s)...\n")
        import asyncio
        for p in profiles:
            if not p["authenticated"] or args.force:
                result = asyncio.run(authenticate_profile_async(p["name"]))
                print(f"  {result.get('message', result)}")
            else:
                print(f'  {p["name"]} ({p["email"]}) — already authenticated')

    print("\n  Done! Server command: google-workspace-mcp\n")


if __name__ == "__main__":
    main()
