#!/usr/bin/env python3
"""Pull change history from Google Ads accounts to learn agency patterns."""

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

# Account IDs
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")
    
    # Calculate date range
    end_date = datetime.now()
    start_date = end_date - timedelta(days=days_back)
    
    query = f"""
        SELECT
            change_event.change_date_time,
            change_event.change_resource_type,
            change_event.changed_fields,
            change_event.client_type,
            change_event.feed,
            change_event.feed_item,
            change_event.resource_change_operation,
            change_event.user_email,
            change_event.old_resource,
            change_event.new_resource,
            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{'='*60}")
    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"{'='*60}\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 by type
        type_counts = {}
        user_counts = {}
        operation_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
        
        print("Changes by type:")
        for t, count in sorted(type_counts.items(), key=lambda x: -x[1]):
            print(f"  {t}: {count}")
        
        print("\nChanges by user:")
        for u, count in sorted(user_counts.items(), key=lambda x: -x[1]):
            print(f"  {u}: {count}")
        
        print("\nChanges by operation:")
        for o, count in sorted(operation_counts.items(), key=lambda x: -x[1]):
            print(f"  {o}: {count}")
            
        # Show recent changes sample
        print(f"\nRecent changes (last 20):")
        for c in changes[:20]:
            print(f"  [{c['date'][:10]}] {c['operation']} {c['type']}")
            if c['campaign']:
                print(f"           Campaign: {c['campaign']}")
            if c['fields']:
                print(f"           Fields: {c['fields']}")
                
    except Exception as e:
        print(f"Error: {e}")
        
    return changes

def get_campaign_performance(client, customer_id, account_name):
    """Pull campaign performance data."""
    ga_service = client.get_service("GoogleAdsService")
    
    query = """
        SELECT
            campaign.id,
            campaign.name,
            campaign.status,
            campaign.advertising_channel_type,
            campaign_budget.amount_micros,
            metrics.cost_micros,
            metrics.conversions,
            metrics.clicks,
            metrics.impressions,
            metrics.cost_per_conversion
        FROM campaign
        WHERE segments.date DURING LAST_30_DAYS
          AND campaign.status != 'REMOVED'
        ORDER BY metrics.cost_micros DESC
    """
    
    print(f"\n{'='*60}")
    print(f"CAMPAIGN PERFORMANCE: {account_name} (Last 30 days)")
    print(f"{'='*60}\n")
    
    try:
        response = ga_service.search(customer_id=customer_id, query=query)
        
        total_cost = 0
        total_conv = 0
        
        print(f"{'Campaign':<40} {'Status':<10} {'Cost':<12} {'Conv':<8} {'CPA':<10}")
        print("-" * 80)
        
        for row in response:
            cost = row.metrics.cost_micros / 1_000_000
            conv = row.metrics.conversions
            cpa = row.metrics.cost_per_conversion / 1_000_000 if conv > 0 else 0
            status = row.campaign.status.name
            
            total_cost += cost
            total_conv += conv
            
            print(f"{row.campaign.name[:40]:<40} {status:<10} ${cost:>10,.2f} {conv:>7.1f} ${cpa:>8.2f}")
        
        print("-" * 80)
        print(f"{'TOTAL':<40} {'':<10} ${total_cost:>10,.2f} {total_conv:>7.1f}")
        
    except Exception as e:
        print(f"Error: {e}")

def main():
    client = GoogleAdsClient.load_from_storage("/Users/dominiquezhoumacmini/.google-ads.yaml")
    
    all_changes = {}
    
    for account_name, customer_id in ACCOUNTS.items():
        # Get change history
        changes = get_change_history(client, customer_id, account_name)
        all_changes[account_name] = changes
        
        # Get current performance
        get_campaign_performance(client, customer_id, account_name)
    
    # Save all changes to JSON for further analysis
    output_file = "/Users/dominiquezhoumacmini/clawd/data/google_ads_change_history.json"
    import os
    os.makedirs(os.path.dirname(output_file), exist_ok=True)
    
    with open(output_file, 'w') as f:
        json.dump(all_changes, f, indent=2, default=str)
    
    print(f"\n\nFull change history saved to: {output_file}")

if __name__ == "__main__":
    main()
