#!/usr/bin/env python3
"""Debug script to test Superset API authentication"""

import json
import requests
from pprint import pprint
from src.core.superset_client import SupersetClient
from src.core.config_manager import ConfigManager


def main():
    print("Debugging Superset API authentication...")
    
    config = ConfigManager()
    
    # Select first available environment
    environments = config.get_environments()
    
    if not environments:
        print("No environments configured")
        return
        
    env = environments[0]
    print(f"\nTesting environment: {env.name}")
    print(f"URL: {env.url}")
    
    try:
        # Test API client authentication
        print("\n--- Testing API Authentication ---")
        client = SupersetClient(env)
        tokens = client.authenticate()
        
        print("\nAPI Auth Success!")
        print(f"Access Token: {tokens.get('access_token', 'N/A')}")
        print(f"CSRF Token: {tokens.get('csrf_token', 'N/A')}")
        
        # Debug cookies from session
        print("\n--- Session Cookies ---")
        for cookie in client.network.session.cookies:
            print(f"{cookie.name}={cookie.value}")
        
        # Test accessing UI via requests
        print("\n--- Testing UI Access ---")
        ui_url = env.url.rstrip('/').replace('/api/v1', '')
        print(f"UI URL: {ui_url}")
        
        # Try to access UI home page
        ui_response = client.network.session.get(ui_url, timeout=30, allow_redirects=True)
        print(f"Status Code: {ui_response.status_code}")
        print(f"URL: {ui_response.url}")
        
        # Check response headers
        print("\n--- Response Headers ---")
        pprint(dict(ui_response.headers))
        
        print(f"\n--- Response Content Preview (200 chars) ---")
        print(repr(ui_response.text[:200]))
        
        if ui_response.status_code == 200:
            print("\nUI Access: Success")
            
            # Try to access a dashboard
            # For testing, just use the home page
            print("\n--- Checking if login is required ---")
            if "login" in ui_response.url.lower() or "login" in ui_response.text.lower():
                print("❌ Not logged in to UI")
            else:
                print("✅ Logged in to UI")
        
    except Exception as e:
        print(f"\n❌ Error: {type(e).__name__}: {e}")
        import traceback
        print("\nStack Trace:")
        print(traceback.format_exc())
        

if __name__ == "__main__":
    main()
