#!/usr/bin/env python3
"""
List all custom events tracked in GA4 property
This queries the GA4 Data API to find what events are available
"""
import json
from datetime import datetime
from pathlib import Path
from google.analytics.data import BetaAnalyticsDataClient
from google.analytics.data_v1beta.types import RunReportRequest, DateRange, Metric, Dimension

CONFIG_DIR = Path(__file__).parent.parent / "config"
GA_CREDENTIALS = CONFIG_DIR / "ga-credentials.json"
GA_PROPERTY_ID = "526394825"

def list_events():
    """Query GA4 for all event names tracked"""
    try:
        client = BetaAnalyticsDataClient.from_service_account_json(str(GA_CREDENTIALS))
        
        # Query for event_name dimension
        request = RunReportRequest(
            property=f"properties/{GA_PROPERTY_ID}",
            dimensions=[Dimension(name="eventName")],
            metrics=[Metric(name="eventCount")],
            date_ranges=[DateRange(start_date="30daysAgo", end_date="today")],
            limit=100
        )
        
        response = client.run_report(request)
        
        events = []
        for row in response.rows:
            event_name = row.dimension_values[0].value
            event_count = int(row.metric_values[0].value)
            events.append((event_name, event_count))
        
        # Sort by event count
        events.sort(key=lambda x: x[1], reverse=True)
        
        return events
        
    except Exception as e:
        print(f"❌ Error: {e}")
        return None

def list_engagement_metrics():
    """Query GA4 for engagement-related metrics"""
    try:
        client = BetaAnalyticsDataClient.from_service_account_json(str(GA_CREDENTIALS))
        
        # Get engagement metrics
        request = RunReportRequest(
            property=f"properties/{GA_PROPERTY_ID}",
            dimensions=[Dimension(name="eventName")],
            metrics=[
                Metric(name="eventCount"),
                Metric(name="totalUsers"),
                Metric(name="eventValue"),
            ],
            date_ranges=[DateRange(start_date="7daysAgo", end_date="today")],
            dimension_filter={
                "filter": {
                    "field_name": "eventName",
                    "string_filter": {
                        "match_type": "CONTAINS",
                        "value": "scroll"
                    }
                }
            },
            limit=50
        )
        
        response = client.run_report(request)
        
        scroll_events = []
        for row in response.rows:
            event_name = row.dimension_values[0].value
            event_count = int(row.metric_values[0].value)
            users = int(row.metric_values[1].value)
            scroll_events.append((event_name, event_count, users))
        
        return scroll_events
        
    except Exception as e:
        return []

if __name__ == "__main__":
    print("🔍 Scanning GA4 Property for Tracked Events...\n")
    print(f"Property ID: {GA_PROPERTY_ID}")
    print(f"Period: Last 30 days\n")
    
    events = list_events()
    
    if events:
        print("📊 Events Found (sorted by count):\n")
        
        # Categorize events
        automatic = []
        enhanced = []
        custom = []
        
        for event_name, count in events:
            if event_name in ['session_start', 'first_visit', 'page_view', 'scroll', 'user_engagement']:
                automatic.append((event_name, count))
            elif event_name in ['click', 'view_search_results']:
                enhanced.append((event_name, count))
            else:
                custom.append((event_name, count))
        
        print("🔹 Automatic Events (GA4 default):")
        for name, count in automatic:
            print(f"  • {name}: {count:,}")
        
        print("\n🔸 Enhanced Measurement Events:")
        if enhanced:
            for name, count in enhanced:
                print(f"  • {name}: {count:,}")
        else:
            print("  (none detected)")
        
        print("\n🎯 Custom Events (your tracking):")
        if custom:
            for name, count in custom:
                print(f"  • {name}: {count:,}")
        else:
            print("  (none detected)")
        
        print("\n" + "="*50)
        print(f"Total unique events: {len(events)}")
        print(f"Time range: Last 30 days")
        
    else:
        print("❌ No events found or error querying GA4")
