#!/usr/bin/env python3
"""
Pull 1 year of Google Ads performance data from old accounts.
"""

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

from google.ads.googleads.client import GoogleAdsClient
import json
import os

# Old accounts with agency history
ACCOUNTS = {
    "US_OLD": ("ZEDE PARIS US", "7480586470"),
    "FR_EU": ("Zede Paris FR/EU", "7441745274"),
}

def get_monthly_performance(client, name, customer_id):
    """Get monthly performance for the past year."""
    ga_service = client.get_service("GoogleAdsService")
    
    query = """
        SELECT
            segments.month,
            metrics.cost_micros,
            metrics.conversions,
            metrics.clicks,
            metrics.impressions,
            metrics.conversions_value
        FROM customer
        WHERE segments.date BETWEEN '2025-01-01' AND '2026-01-26'
        ORDER BY segments.month
    """
    
    print(f"\n{'='*70}")
    print(f"📅 MONTHLY PERFORMANCE: {name}")
    print(f"{'='*70}\n")
    
    months = []
    try:
        response = ga_service.search(customer_id=customer_id, query=query)
        
        print(f"{'Month':<12} {'Spend':>12} {'Conv':>8} {'CPA':>10} {'Value':>12} {'ROAS':>8}")
        print("-" * 70)
        
        for row in response:
            month = row.segments.month
            cost = row.metrics.cost_micros / 1_000_000
            conv = row.metrics.conversions
            value = row.metrics.conversions_value
            cpa = cost / conv if conv > 0 else 0
            roas = value / cost if cost > 0 else 0
            
            months.append({
                "month": month,
                "cost": cost,
                "conversions": conv,
                "value": value,
                "cpa": cpa,
                "roas": roas,
            })
            
            print(f"{month:<12} ${cost:>11,.0f} {conv:>7.0f} ${cpa:>9,.0f} ${value:>11,.0f} {roas:>7.1f}x")
        
        # Totals
        total_cost = sum(m["cost"] for m in months)
        total_conv = sum(m["conversions"] for m in months)
        total_value = sum(m["value"] for m in months)
        avg_cpa = total_cost / total_conv if total_conv > 0 else 0
        total_roas = total_value / total_cost if total_cost > 0 else 0
        
        print("-" * 70)
        print(f"{'TOTAL':<12} ${total_cost:>11,.0f} {total_conv:>7.0f} ${avg_cpa:>9,.0f} ${total_value:>11,.0f} {total_roas:>7.1f}x")
        
    except Exception as e:
        print(f"Error: {e}")
    
    return months


def get_campaign_history(client, name, customer_id):
    """Get campaign performance over the year."""
    ga_service = client.get_service("GoogleAdsService")
    
    query = """
        SELECT
            campaign.name,
            campaign.status,
            metrics.cost_micros,
            metrics.conversions,
            metrics.conversions_value
        FROM campaign
        WHERE segments.date BETWEEN '2025-01-01' AND '2026-01-26'
        ORDER BY metrics.cost_micros DESC
    """
    
    print(f"\n{'='*70}")
    print(f"📊 CAMPAIGN TOTALS (Year): {name}")
    print(f"{'='*70}\n")
    
    campaigns = []
    try:
        response = ga_service.search(customer_id=customer_id, query=query)
        
        print(f"{'Campaign':<40} {'Spend':>12} {'Conv':>8} {'CPA':>10}")
        print("-" * 75)
        
        for row in response:
            cost = row.metrics.cost_micros / 1_000_000
            conv = row.metrics.conversions
            cpa = cost / conv if conv > 0 else 0
            
            if cost > 100:  # Only show campaigns with significant spend
                campaigns.append({
                    "name": row.campaign.name,
                    "status": row.campaign.status.name,
                    "cost": cost,
                    "conversions": conv,
                    "cpa": cpa,
                })
                
                print(f"{row.campaign.name[:40]:<40} ${cost:>11,.0f} {conv:>7.0f} ${cpa:>9,.0f}")
        
    except Exception as e:
        print(f"Error: {e}")
    
    return campaigns


def get_keyword_history(client, name, customer_id):
    """Get top keywords over the year."""
    ga_service = client.get_service("GoogleAdsService")
    
    query = """
        SELECT
            ad_group_criterion.keyword.text,
            ad_group_criterion.keyword.match_type,
            metrics.cost_micros,
            metrics.conversions,
            metrics.clicks
        FROM keyword_view
        WHERE segments.date BETWEEN '2025-01-01' AND '2026-01-26'
        ORDER BY metrics.cost_micros DESC
        LIMIT 50
    """
    
    print(f"\n{'='*70}")
    print(f"🔑 TOP KEYWORDS (Year): {name}")
    print(f"{'='*70}\n")
    
    keywords = []
    zero_conv_total = 0
    
    try:
        response = ga_service.search(customer_id=customer_id, query=query)
        
        print(f"{'Keyword':<35} {'Match':<8} {'Spend':>10} {'Conv':>6} {'CPA':>8}")
        print("-" * 75)
        
        for row in response:
            cost = row.metrics.cost_micros / 1_000_000
            conv = row.metrics.conversions
            cpa = cost / conv if conv > 0 else 0
            match = row.ad_group_criterion.keyword.match_type.name
            
            if conv == 0:
                zero_conv_total += cost
            
            keywords.append({
                "keyword": row.ad_group_criterion.keyword.text,
                "match": match,
                "cost": cost,
                "conversions": conv,
            })
            
            flag = "⚠️" if conv == 0 and cost > 200 else ""
            print(f"{row.ad_group_criterion.keyword.text[:35]:<35} {match:<8} ${cost:>9,.0f} {conv:>5.0f} ${cpa:>7,.0f} {flag}")
        
        print(f"\n💰 Total zero-conversion keyword spend (year): ${zero_conv_total:,.0f}")
        
    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 key, (name, cid) in ACCOUNTS.items():
        all_data[key] = {
            "monthly": get_monthly_performance(client, name, cid),
            "campaigns": get_campaign_history(client, name, cid),
            "keywords": get_keyword_history(client, name, cid),
        }
    
    # Save to JSON
    output_file = "/Users/dominiquezhoumacmini/clawd/data/google_ads_yearly_history.json"
    os.makedirs(os.path.dirname(output_file), exist_ok=True)
    
    with open(output_file, 'w') as f:
        json.dump(all_data, f, indent=2, default=str)
    
    print(f"\n\n✅ Full yearly data saved to: {output_file}")


if __name__ == "__main__":
    main()
