#!/usr/bin/env python3
"""
One-time WHOOP OAuth2 authorization setup.

This script:
1. Opens your browser to authorize with WHOOP
2. Captures the OAuth callback
3. Stores tokens securely in macOS Keychain AND file (for cron access)

Prerequisites:
1. Create a WHOOP developer app at https://developer-dashboard.whoop.com
2. Set redirect URI to: http://localhost:8765/callback
3. Copy .env.example to .env and add your Client ID and Secret

Usage:
    python scripts/setup_auth.py          # Full authorization flow
    python scripts/setup_auth.py --force  # Force re-authorization (skip prompt)
    python scripts/setup_auth.py --sync   # Copy keychain tokens to file (for cron)
    python scripts/setup_auth.py --status # Show token storage status
"""

import argparse
import os
import sys

# Add parent directory to path for imports
sys.path.insert(0, os.path.join(os.path.dirname(__file__), "..", "src"))

from whoop_mcp.auth import get_auth_from_env, HybridTokenStorage, TOKEN_FILE


def show_status():
    """Show current token storage status."""
    print("=" * 60)
    print("WHOOP Token Storage Status")
    print("=" * 60)
    print()

    status = HybridTokenStorage.get_storage_status()

    print("Keychain:")
    if status["keychain"]["available"]:
        from datetime import datetime
        expires = datetime.fromtimestamp(status["keychain"]["expires_at"])
        print(f"  Status: Available")
        print(f"  Expires: {expires.strftime('%Y-%m-%d %H:%M:%S')}")
    else:
        print(f"  Status: Not available (may fail in cron context)")

    print()
    print("File:")
    print(f"  Path: {status['file']['path']}")
    if status["file"]["available"]:
        from datetime import datetime
        expires = datetime.fromtimestamp(status["file"]["expires_at"])
        print(f"  Status: Available")
        print(f"  Expires: {expires.strftime('%Y-%m-%d %H:%M:%S')}")
    else:
        print(f"  Status: Not available")

    print()
    if status["keychain"]["available"] and not status["file"]["available"]:
        print("TIP: Run 'setup_auth.py --sync' to copy keychain tokens to file for cron access.")
    elif status["file"]["available"]:
        print("Cron jobs should work - file-based tokens available.")


def sync_tokens():
    """Copy tokens from keychain to file for cron access."""
    print("=" * 60)
    print("Syncing Keychain Tokens to File")
    print("=" * 60)
    print()

    if HybridTokenStorage.sync_keychain_to_file():
        print("SUCCESS! Tokens copied from keychain to file.")
        print()
        print(f"File location: {TOKEN_FILE}")
        print("File permissions: 600 (owner read/write only)")
        print()
        print("Cron jobs can now access WHOOP tokens.")
    else:
        print("FAILED. Could not sync tokens.")
        print()
        print("Make sure you have valid tokens in keychain first.")
        print("Run 'setup_auth.py' without flags to authorize.")
        sys.exit(1)


def main():
    parser = argparse.ArgumentParser(description="WHOOP OAuth2 authorization setup")
    parser.add_argument("--sync", action="store_true",
                        help="Copy keychain tokens to file (for cron jobs)")
    parser.add_argument("--status", action="store_true",
                        help="Show token storage status")
    parser.add_argument("--force", action="store_true",
                        help="Force re-authorization without prompting")
    args = parser.parse_args()

    if args.status:
        show_status()
        return

    if args.sync:
        sync_tokens()
        return

    # Full authorization flow
    print("=" * 60)
    print("WHOOP OAuth2 Authorization Setup")
    print("=" * 60)
    print()

    # Check for existing authorization
    existing_tokens = HybridTokenStorage.get_tokens()
    if existing_tokens:
        print("Existing authorization found.")
        if args.force:
            print("Force flag set, re-authorizing...")
        else:
            response = input("Do you want to re-authorize? (y/N): ").strip().lower()
            if response != "y":
                print("Keeping existing authorization. Exiting.")
                return

        print("Clearing existing tokens...")
        HybridTokenStorage.clear_tokens()
        print()

    # Get auth handler
    try:
        auth = get_auth_from_env()
    except ValueError as e:
        print(f"Error: {e}")
        print()
        print("Setup instructions:")
        print("1. Copy .env.example to .env")
        print("2. Add your WHOOP_CLIENT_ID and WHOOP_CLIENT_SECRET")
        print("3. Run this script again")
        sys.exit(1)

    print("Starting authorization flow...")
    print("This will open your browser to authorize with WHOOP.")
    print()

    # Start OAuth flow
    success = auth.start_authorization_flow()

    if success:
        print()
        print("=" * 60)
        print("SUCCESS! Authorization complete.")
        print("=" * 60)
        print()
        print("Tokens stored in:")
        print("  - macOS Keychain (for interactive use)")
        print(f"  - {TOKEN_FILE} (for cron jobs)")
        print()
        print("The MCP server will automatically refresh tokens as needed.")
        print("You can now use the WHOOP MCP server with Claude Code.")
    else:
        print()
        print("=" * 60)
        print("FAILED. Authorization was not completed.")
        print("=" * 60)
        print()
        print("Please try again. Make sure:")
        print("1. Your redirect URI is set to http://localhost:8765/callback")
        print("2. Your Client ID and Secret are correct")
        print("3. You complete the authorization in your browser")
        sys.exit(1)


if __name__ == "__main__":
    main()
