#!/usr/bin/env python3
"""Full Google Ads analysis - change history (30 days) + historical performance."""

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
import os

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

def get_change_history(client, customer_id, account_name):
    """Pull last 30 days of change history."""
    ga_service = client.get_service("GoogleAdsService")
    
    end_date = datetime.now()
    start_date = end_date - timedelta(days=29)  # Max 30 days
    
    query = f"""
        SELECT
            change_event.change_date_time,
            change_event.change_resource_type,
            change_event.changed_fields,
            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 5000
    """
    
    print(f"\n{'='*70}")
    print(f"📝 CHANGE HISTORY (Last 30 Days): {account_name}")
    print(f"{'='*70}\n")
    
    changes = []
    try:
        response = ga_service.search(customer_id=customer_id, query=query)
        
        for row in response:
            changes.append({
                "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,
            })
            
        print(f"Found {len(changes)} changes\n")
        
        # Summarize
        type_counts = {}
        user_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
        
        print("By type:")
        for t, count in sorted(type_counts.items(), key=lambda x: -x[1])[:10]:
            print(f"  {t}: {count}")
        
        print("\nBy user (agency vs you):")
        for u, count in sorted(user_counts.items(), key=lambda x: -x[1]):
            print(f"  {u}: {count}")
            
    except Exception as e:
        print(f"Error: {e}")
        
    return changes


def get_campaign_performance(client, customer_id, account_name, days=90):
    """Pull campaign performance over time."""
    ga_service = client.get_service("GoogleAdsService")
    
    query = f"""
        SELECT
            segments.date,
            campaign.id,
            campaign.name,
            campaign.status,
            campaign.bidding_strategy_type,
            metrics.cost_micros,
            metrics.conversions,
            metrics.clicks,
            metrics.impressions
        FROM campaign
        WHERE segments.date DURING LAST_{days}_DAYS
          AND campaign.status != 'REMOVED'
        ORDER BY segments.date DESC
    """
    
    print(f"\n{'='*70}")
    print(f"📈 CAMPAIGN PERFORMANCE (Last {days} Days): {account_name}")
    print(f"{'='*70}\n")
    
    data = []
    try:
        response = ga_service.search(customer_id=customer_id, query=query)
        
        campaigns = {}
        for row in response:
            name = row.campaign.name
            if name not in campaigns:
                campaigns[name] = {
                    "name": name,
                    "status": row.campaign.status.name,
                    "bidding": row.campaign.bidding_strategy_type.name,
                    "cost": 0,
                    "conversions": 0,
                    "clicks": 0,
                    "impressions": 0,
                }
            campaigns[name]["cost"] += row.metrics.cost_micros / 1_000_000
            campaigns[name]["conversions"] += row.metrics.conversions
            campaigns[name]["clicks"] += row.metrics.clicks
            campaigns[name]["impressions"] += row.metrics.impressions
        
        # Sort by cost
        sorted_campaigns = sorted(campaigns.values(), key=lambda x: -x["cost"])
        
        print(f"{'Campaign':<45} {'Status':<8} {'Bidding':<20} {'Cost':>10} {'Conv':>6} {'CPA':>8}")
        print("-" * 105)
        
        for c in sorted_campaigns:
            cpa = c["cost"] / c["conversions"] if c["conversions"] > 0 else 0
            print(f"{c['name'][:45]:<45} {c['status']:<8} {c['bidding'][:20]:<20} ${c['cost']:>9,.0f} {c['conversions']:>5.0f} ${cpa:>7.0f}")
            data.append(c)
            
    except Exception as e:
        print(f"Error: {e}")
        
    return data


def get_keyword_performance(client, customer_id, account_name):
    """Pull keyword performance to identify wasted spend."""
    ga_service = client.get_service("GoogleAdsService")
    
    query = """
        SELECT
            ad_group_criterion.keyword.text,
            ad_group_criterion.keyword.match_type,
            ad_group_criterion.status,
            campaign.name,
            ad_group.name,
            metrics.cost_micros,
            metrics.conversions,
            metrics.clicks,
            metrics.impressions
        FROM keyword_view
        WHERE segments.date DURING LAST_90_DAYS
          AND metrics.cost_micros > 0
        ORDER BY metrics.cost_micros DESC
        LIMIT 200
    """
    
    print(f"\n{'='*70}")
    print(f"🔑 TOP KEYWORDS BY SPEND: {account_name}")
    print(f"{'='*70}\n")
    
    keywords = []
    try:
        response = ga_service.search(customer_id=customer_id, query=query)
        
        print(f"{'Keyword':<35} {'Match':<8} {'Cost':>10} {'Conv':>6} {'CPA':>8} {'Status':<8}")
        print("-" * 85)
        
        zero_conv_cost = 0
        
        for row in response:
            cost = row.metrics.cost_micros / 1_000_000
            conv = row.metrics.conversions
            cpa = cost / conv if conv > 0 else 0
            
            kw = {
                "keyword": row.ad_group_criterion.keyword.text,
                "match": row.ad_group_criterion.keyword.match_type.name,
                "campaign": row.campaign.name,
                "cost": cost,
                "conversions": conv,
                "status": row.ad_group_criterion.status.name,
            }
            keywords.append(kw)
            
            if conv == 0:
                zero_conv_cost += cost
            
            # Only print top 30
            if len(keywords) <= 30:
                flag = "⚠️" if conv == 0 and cost > 100 else ""
                print(f"{row.ad_group_criterion.keyword.text[:35]:<35} {kw['match']:<8} ${cost:>9,.0f} {conv:>5.0f} ${cpa:>7.0f} {kw['status']:<8} {flag}")
        
        print(f"\n💰 Zero-conversion keywords (90d): ${zero_conv_cost:,.0f} wasted")
            
    except Exception as e:
        print(f"Error: {e}")
        
    return keywords


def main():
    client = GoogleAdsClient.load_from_storage("/Users/dominiquezhoumacmini/.google-ads.yaml")
    
    all_data = {}
    
    for account_name, customer_id in ACCOUNTS.items():
        all_data[account_name] = {
            "changes": get_change_history(client, customer_id, account_name),
            "campaigns": get_campaign_performance(client, customer_id, account_name),
            "keywords": get_keyword_performance(client, customer_id, account_name),
        }
    
    # Save
    output_dir = "/Users/dominiquezhoumacmini/clawd/data"
    os.makedirs(output_dir, exist_ok=True)
    
    output_file = f"{output_dir}/google_ads_full_analysis.json"
    with open(output_file, 'w') as f:
        json.dump(all_data, f, indent=2, default=str)
    
    print(f"\n\n✅ Full analysis saved to: {output_file}")

if __name__ == "__main__":
    main()
