#!/usr/bin/env python3
"""
Set CORS on Firebase Storage bucket.

Usage: python set_storage_cors.py <project_id> <origin> [<origin2> ...]

Example:
  python set_storage_cors.py symph-my-app https://my-app.dev.apps.symph.co
  python set_storage_cors.py symph-my-app https://my-app.dev.apps.symph.co http://localhost:3000
"""

import sys
import json
import os
from google.cloud import storage
from google.oauth2 import service_account

def set_cors(project_id: str, origins: list[str]):
    """Set CORS configuration on Firebase Storage bucket."""
    
    # Set credentials
    credentials_path = os.path.expanduser("~/.config/gcloud/aria-firebase-admin.json")
    credentials = service_account.Credentials.from_service_account_file(credentials_path)
    
    # Create client
    client = storage.Client(credentials=credentials, project=project_id)
    
    # Bucket name is project_id.appspot.com
    bucket_name = f"{project_id}.appspot.com"
    bucket = client.bucket(bucket_name)
    
    # Always include localhost for development
    all_origins = list(set(origins + ["http://localhost:3000", "http://localhost:3003"]))
    
    # Set CORS config
    cors_config = [
        {
            "origin": all_origins,
            "method": ["GET", "POST", "PUT", "DELETE", "HEAD", "OPTIONS"],
            "maxAgeSeconds": 3600,
            "responseHeader": [
                "Content-Type",
                "Authorization", 
                "Content-Length",
                "User-Agent",
                "x-goog-resumable",
                "x-firebase-storage-version"
            ]
        }
    ]
    
    bucket.cors = cors_config
    bucket.patch()
    
    print(f"✅ CORS configured on {bucket_name}")
    print(f"   Origins: {', '.join(all_origins)}")
    return True

if __name__ == "__main__":
    if len(sys.argv) < 3:
        print(__doc__)
        sys.exit(1)
    
    project_id = sys.argv[1]
    origins = sys.argv[2:]
    
    try:
        set_cors(project_id, origins)
    except Exception as e:
        print(f"❌ Error: {e}")
        sys.exit(1)
