#!/usr/bin/env python3
"""
Oura Ring API setup — one-time token configuration.

Steps:
  1. Go to https://cloud.ouraring.com/personal-access-tokens
  2. Log in with your Oura account
  3. Click "Create New Personal Access Token"
  4. Copy the token
  5. Run this script and paste it

Usage:
  python3 setup_oura_auth.py
"""

import json
import os
import ssl
import sys
import urllib.request
import urllib.error
from pathlib import Path

TOKEN_PATH = Path(__file__).resolve().parent.parent / ".oura-token.json"
BASE_URL = "https://api.ouraring.com"


def _get_ssl_context():
    """Build SSL context that works on macOS (cert discovery)."""
    try:
        import certifi
        return ssl.create_default_context(cafile=certifi.where())
    except ImportError:
        pass

    # Try common macOS/brew cert locations
    for cert_path in [
        "/etc/ssl/cert.pem",
        "/usr/local/etc/openssl/cert.pem",
        "/usr/local/etc/openssl@3/cert.pem",
        "/opt/homebrew/etc/openssl@3/cert.pem",
        "/opt/homebrew/etc/openssl/cert.pem",
    ]:
        if os.path.exists(cert_path):
            return ssl.create_default_context(cafile=cert_path)

    return ssl.create_default_context()


def main():
    print("=" * 50)
    print("  Oura Ring API Setup")
    print("=" * 50)
    print()
    print("1. Go to: https://cloud.ouraring.com/personal-access-tokens")
    print("2. Log in and create a new Personal Access Token")
    print("3. Copy the token and paste it below")
    print()

    token = input("Paste your Oura access token: ").strip()
    if not token:
        print("No token entered. Exiting.")
        sys.exit(1)

    ctx = _get_ssl_context()

    # Test the token
    print("\nTesting token...")
    try:
        req = urllib.request.Request(
            f"{BASE_URL}/v2/usercollection/personal_info",
            headers={
                "Authorization": f"Bearer {token}",
                "Accept": "application/json",
            },
        )
        with urllib.request.urlopen(req, timeout=10, context=ctx) as resp:
            info = json.loads(resp.read())

        print(f"  Connected to Oura account: {info.get('email', 'unknown')}")
        print(f"  Age: {info.get('age', '?')}")
    except urllib.error.HTTPError as e:
        if e.code == 401:
            print("  ERROR: Token is invalid or expired.")
            print("  Please generate a new token at cloud.ouraring.com")
        else:
            print(f"  ERROR: API returned {e.code}: {e.reason}")
        sys.exit(1)
    except urllib.error.URLError as e:
        # SSL still failing — offer to install certifi
        if "CERTIFICATE_VERIFY_FAILED" in str(e):
            print(f"  SSL certificate error: {e}")
            print()
            print("  Fix: run one of these commands:")
            print("    pip3 install certifi")
            print("  or:")
            print("    /Applications/Python*/Install\\ Certificates.command")
            print()
            print("  Then re-run this script.")
        else:
            print(f"  ERROR: Could not connect to Oura API: {e}")
        sys.exit(1)
    except Exception as e:
        print(f"  ERROR: Could not connect to Oura API: {e}")
        sys.exit(1)

    # Test sleep endpoint
    print("\nTesting sleep data access...")
    try:
        from datetime import date, timedelta
        yesterday = (date.today() - timedelta(days=1)).isoformat()
        today = date.today().isoformat()
        req = urllib.request.Request(
            f"{BASE_URL}/v2/usercollection/sleep?start_date={yesterday}&end_date={today}",
            headers={
                "Authorization": f"Bearer {token}",
                "Accept": "application/json",
            },
        )
        with urllib.request.urlopen(req, timeout=10, context=ctx) as resp:
            sleep_data = json.loads(resp.read())

        sessions = sleep_data.get("data", [])
        if sessions:
            latest = sessions[-1]
            hours = round(latest.get("total_sleep_duration", 0) / 3600, 1)
            print(f"  Last night's sleep: {hours}h")
        else:
            print("  No sleep data for last night (normal if ring wasn't worn)")
    except Exception as e:
        print(f"  Sleep data test: {e} (non-fatal)")

    # Save token
    token_data = {"access_token": token}
    TOKEN_PATH.write_text(json.dumps(token_data, indent=2))
    print(f"\nToken saved to: {TOKEN_PATH}")
    print("\nSetup complete! Luke will now pull health data from Oura at 8 AM daily.")
    print("You can also text Luke 'oura' anytime to trigger a manual pull.")


if __name__ == "__main__":
    main()
