#!/usr/bin/env python3
"""Pull change history from Google Ads accounts - fixed query."""

import sys
sys.path.insert(0, '/Users/dominiquezhoumacmini/Library/Python/3.9/lib/python/site-packages')

from google.ads.googleads.client import GoogleAdsClient
from datetime import datetime, timedelta
import json

ACCOUNTS = {
    "FR_EU": "7441745274",
    "US_OLD": "7480586470",
}

def get_change_history(client, customer_id, account_name, days_back=365):
    """Pull change history for an account."""
    ga_service = client.get_service("GoogleAdsService")
    
    end_date = datetime.now()
    start_date = end_date - timedelta(days=days_back)
    
    # Fixed query without deprecated fields
    query = f"""
        SELECT
            change_event.change_date_time,
            change_event.change_resource_type,
            change_event.changed_fields,
            change_event.client_type,
            change_event.resource_change_operation,
            change_event.user_email,
            campaign.name,
            ad_group.name
        FROM change_event
        WHERE change_event.change_date_time >= '{start_date.strftime("%Y-%m-%d")}'
          AND change_event.change_date_time <= '{end_date.strftime("%Y-%m-%d")}'
        ORDER BY change_event.change_date_time DESC
        LIMIT 10000
    """
    
    print(f"\n{'='*70}")
    print(f"CHANGE HISTORY: {account_name} ({customer_id})")
    print(f"Period: {start_date.strftime('%Y-%m-%d')} to {end_date.strftime('%Y-%m-%d')}")
    print(f"{'='*70}\n")
    
    changes = []
    try:
        response = ga_service.search(customer_id=customer_id, query=query)
        
        for row in response:
            change = {
                "date": row.change_event.change_date_time,
                "type": row.change_event.change_resource_type.name,
                "operation": row.change_event.resource_change_operation.name,
                "user": row.change_event.user_email,
                "fields": row.change_event.changed_fields,
                "campaign": row.campaign.name if row.campaign.name else None,
                "ad_group": row.ad_group.name if row.ad_group.name else None,
            }
            changes.append(change)
            
        print(f"Found {len(changes)} changes\n")
        
        # Summarize
        type_counts = {}
        user_counts = {}
        operation_counts = {}
        monthly_counts = {}
        
        for c in changes:
            type_counts[c["type"]] = type_counts.get(c["type"], 0) + 1
            user_counts[c["user"]] = user_counts.get(c["user"], 0) + 1
            operation_counts[c["operation"]] = operation_counts.get(c["operation"], 0) + 1
            month = c["date"][:7] if c["date"] else "unknown"
            monthly_counts[month] = monthly_counts.get(month, 0) + 1
        
        print("📊 Changes by type:")
        for t, count in sorted(type_counts.items(), key=lambda x: -x[1])[:10]:
            print(f"  {t}: {count}")
        
        print("\n👤 Changes by user:")
        for u, count in sorted(user_counts.items(), key=lambda x: -x[1]):
            print(f"  {u}: {count}")
        
        print("\n🔧 Changes by operation:")
        for o, count in sorted(operation_counts.items(), key=lambda x: -x[1]):
            print(f"  {o}: {count}")
            
        print("\n📅 Changes by month:")
        for m, count in sorted(monthly_counts.items()):
            print(f"  {m}: {count}")
            
    except Exception as e:
        print(f"Error: {e}")
        
    return changes

def main():
    client = GoogleAdsClient.load_from_storage("/Users/dominiquezhoumacmini/.google-ads.yaml")
    
    all_changes = {}
    
    for account_name, customer_id in ACCOUNTS.items():
        changes = get_change_history(client, customer_id, account_name)
        all_changes[account_name] = changes
    
    # Save
    output_file = "/Users/dominiquezhoumacmini/clawd/data/google_ads_change_history.json"
    with open(output_file, 'w') as f:
        json.dump(all_changes, f, indent=2, default=str)
    
    print(f"\n\n✅ Full change history saved to: {output_file}")

if __name__ == "__main__":
    main()
