"""Firebase Admin SDK authentication."""
import firebase_admin
from firebase_admin import credentials, auth
import os
from typing import Optional, Dict
from api.firestore_db import (
    get_user_by_email, create_user, get_organization, create_organization,
    create_org_member, get_org_members
)
from api.constants import Plan, Role
import uuid

# Initialize Firebase Admin (only once)
if not firebase_admin._apps:
    cred_path = os.getenv("FIREBASE_ADMIN_CREDENTIALS_PATH")
    if cred_path and os.path.exists(cred_path):
        cred = credentials.Certificate(cred_path)
        firebase_admin.initialize_app(cred)
        print("✅ Firebase Admin initialized with service account")
    else:
        # For development, you can use service account JSON
        # Download from Firebase Console → Project Settings → Service Accounts
        print("⚠️  FIREBASE_ADMIN_CREDENTIALS_PATH not set or file not found")
        print("   Firebase Admin will not work until you set this environment variable")
        # Don't initialize if credentials are missing
        # firebase_admin.initialize_app()


def verify_firebase_token(token: str) -> Optional[dict]:
    """Verify Firebase ID token and return decoded token."""
    if not firebase_admin._apps:
        return None
    
    try:
        decoded_token = auth.verify_id_token(token)
        return decoded_token
    except Exception as e:
        print(f"Firebase token verification error: {e}")
        return None


def get_user_from_firebase_token(token: str, db=None) -> Optional[Dict]:
    """Get or create user from Firebase token (db parameter kept for compatibility but not used)."""
    decoded = verify_firebase_token(token)
    if not decoded:
        return None
    
    email = decoded.get('email')
    firebase_uid = decoded.get('uid')
    
    if not email:
        return None
    
    # Find or create user in Firestore
    user = get_user_by_email(email)
    if not user:
        # Create user (no password needed - Firebase handles auth)
        user_data = {
            'id': str(uuid.uuid4()),
            'email': email,
            'password_hash': '',  # Not used with Firebase
            'name': decoded.get('name'),
            'email_verified': decoded.get('email_verified', False),
            'subscription_plan': None,
            'subscription_status': 'inactive'
        }
        user = create_user(user_data)
        
        # Create default organization for new user
        org_data = {
            'id': str(uuid.uuid4()),
            'name': f"Organization for {email}",
            'plan': Plan.FREE.value
        }
        org = create_organization(org_data)
        
        # Add user as owner
        member_data = {
            'id': str(uuid.uuid4()),
            'user_id': user['id'],
            'organization_id': org['id'],
            'role': Role.OWNER.value
        }
        create_org_member(member_data)
        
        print(f"✅ Created user and organization for {email}")
    
    return user

