#!/usr/bin/env python3
"""
Enhanced authentication setup for Gmail + Calendar + Notion access.
Ensures reliable authentication without daily re-authentication.
"""

import os
import sys
import json
from pathlib import Path

try:
    from google.auth.transport.requests import Request
    from google.oauth2.credentials import Credentials
    from google_auth_oauthlib.flow import InstalledAppFlow
except ImportError:
    print("Error: Google API libraries not installed.")
    print("Run: pip install google-auth google-auth-oauthlib google-auth-httplib2 google-api-python-client")
    sys.exit(1)

# Extended scopes for Gmail + Calendar
SCOPES = [
    'https://www.googleapis.com/auth/gmail.readonly',
    'https://www.googleapis.com/auth/gmail.send', 
    'https://www.googleapis.com/auth/gmail.modify',
    'https://www.googleapis.com/auth/calendar.readonly',
    'https://www.googleapis.com/auth/calendar.events'
]

# Paths
SKILLS_DIR = Path.home() / '.clawdbot' / 'skills'
GMAIL_DIR = SKILLS_DIR / 'gmail'
TOKENS_DIR = GMAIL_DIR / 'tokens'
NOTION_CONFIG = Path.home() / '.config' / 'notion'

def setup_gmail_calendar():
    """Set up Gmail + Calendar authentication with cos.json token."""
    print("🔧 Setting up Gmail + Calendar authentication...")
    
    TOKENS_DIR.mkdir(parents=True, exist_ok=True)
    credentials_file = GMAIL_DIR / 'credentials.json'
    cos_token_file = TOKENS_DIR / 'cos.json'
    
    if not credentials_file.exists():
        print(f"❌ Missing credentials.json at {credentials_file}")
        print("\nSetup instructions:")
        print("1. Go to https://console.cloud.google.com/")
        print("2. Enable Gmail API + Calendar API")
        print("3. Create OAuth credentials (Desktop app)")
        print(f"4. Save as {credentials_file}")
        return False
        
    # Authenticate with new scopes
    creds = None
    if cos_token_file.exists():
        creds = Credentials.from_authorized_user_file(str(cos_token_file), SCOPES)
    
    if not creds or not creds.valid:
        if creds and creds.expired and creds.refresh_token:
            try:
                creds.refresh(Request())
            except:
                creds = None
        
        if not creds:
            flow = InstalledAppFlow.from_client_secrets_file(str(credentials_file), SCOPES)
            creds = flow.run_local_server(port=0)
    
    # Save credentials
    cos_token_file.write_text(creds.to_json())
    print(f"✅ Gmail + Calendar authentication saved to {cos_token_file}")
    
    # Verify scopes
    token_data = json.loads(cos_token_file.read_text())
    current_scopes = token_data.get('scopes', [])
    print(f"📋 Active scopes: {len(current_scopes)} scopes")
    for scope in current_scopes:
        if 'gmail' in scope:
            print(f"  📧 {scope}")
        elif 'calendar' in scope:
            print(f"  📅 {scope}")
    
    return True

def verify_notion():
    """Verify Notion API key exists."""
    print("\n🔧 Checking Notion authentication...")
    
    api_key_file = NOTION_CONFIG / 'api_key'
    if api_key_file.exists():
        api_key = api_key_file.read_text().strip()
        if api_key.startswith('ntn_') or api_key.startswith('secret_'):
            print("✅ Notion API key found and valid format")
            return True
    
    print("❌ Notion API key missing or invalid")
    print(f"Expected location: {api_key_file}")
    print("Get your key from: https://notion.so/my-integrations")
    return False

def update_heartbeat():
    """Update HEARTBEAT.md with current status."""
    print("\n🔧 Updating HEARTBEAT.md...")
    
    heartbeat_file = Path.cwd() / 'HEARTBEAT.md'
    if not heartbeat_file.exists():
        print("❌ HEARTBEAT.md not found")
        return
        
    # Add authentication status
    content = heartbeat_file.read_text()
    if "## 🔧 Authentication Status" not in content:
        timestamp = "2026-01-28"
        auth_section = f"""

## 🔧 Authentication Status (Updated {timestamp})
- **Gmail + Calendar:** ✅ cos.json with extended scopes
- **Notion:** ✅ API key configured  
- **Auto-authentication:** ✅ No daily re-auth needed
"""
        
        # Insert before first ## section
        lines = content.split('\n')
        for i, line in enumerate(lines):
            if line.startswith('## ') and i > 5:  # Skip header sections
                lines.insert(i, auth_section)
                break
        
        heartbeat_file.write_text('\n'.join(lines))
        print("✅ HEARTBEAT.md updated with auth status")

def create_auth_helper():
    """Create a helper script for future authentication issues."""
    print("\n🔧 Creating authentication helper...")
    
    helper_script = Path.cwd() / 'auth_check.py'
    helper_content = '''#!/usr/bin/env python3
"""Quick authentication status checker."""

import json
from pathlib import Path
from datetime import datetime

def check_auth_status():
    print("🔍 Authentication Status Check")
    print("=" * 40)
    
    # Check Gmail/Calendar
    cos_token = Path.home() / '.clawdbot' / 'skills' / 'gmail' / 'tokens' / 'cos.json'
    if cos_token.exists():
        try:
            token_data = json.loads(cos_token.read_text())
            scopes = token_data.get('scopes', [])
            expiry = token_data.get('expiry', 'Unknown')
            
            print(f"📧 Gmail/Calendar: ✅ Active ({len(scopes)} scopes)")
            print(f"   Expires: {expiry}")
            
            gmail_scopes = [s for s in scopes if 'gmail' in s]
            calendar_scopes = [s for s in scopes if 'calendar' in s]
            print(f"   Gmail scopes: {len(gmail_scopes)}")
            print(f"   Calendar scopes: {len(calendar_scopes)}")
            
        except Exception as e:
            print(f"📧 Gmail/Calendar: ❌ Error reading token - {e}")
    else:
        print("📧 Gmail/Calendar: ❌ No token found")
    
    # Check Notion
    notion_key = Path.home() / '.config' / 'notion' / 'api_key'
    if notion_key.exists():
        key = notion_key.read_text().strip()[:20] + "..."
        print(f"📝 Notion: ✅ API key found ({key})")
    else:
        print("📝 Notion: ❌ No API key found")

if __name__ == "__main__":
    check_auth_status()
'''
    
    helper_script.write_text(helper_content)
    helper_script.chmod(0o755)
    print(f"✅ Created {helper_script}")

def main():
    print("🚀 Enhanced Authentication Setup")
    print("=" * 50)
    
    gmail_ok = setup_gmail_calendar()
    notion_ok = verify_notion()
    
    if gmail_ok and notion_ok:
        print("\n🎉 All authentication configured successfully!")
        update_heartbeat()
        create_auth_helper()
        
        print("\n📋 Next steps:")
        print("1. Test with: GMAIL_ACCOUNT=cos python3 ~/.clawdbot/skills/gmail/scripts/gmail.py whoami")
        print("2. Test Notion: curl with your API key")
        print("3. Run: python3 auth_check.py (anytime to verify status)")
        
    else:
        print("\n❌ Authentication setup incomplete.")
        print("Fix the issues above and re-run this script.")

if __name__ == "__main__":
    main()