#!/usr/bin/env python3
"""
Weekly Google Ads Performance Report
Generates comprehensive summary for all accounts.
"""

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

ACCOUNTS = {
    "US_NEW": ("Elde Ventures LLC", "2949069258"),
    "US_OLD": ("ZEDE PARIS US", "7480586470"),
    "FR_EU": ("Zede Paris FR/EU", "7441745274"),
}

def get_account_performance(client, name, customer_id):
    """Get performance metrics for an account."""
    ga_service = client.get_service("GoogleAdsService")
    
    # This week
    query_this = """
        SELECT
            metrics.cost_micros,
            metrics.conversions,
            metrics.clicks,
            metrics.impressions
        FROM customer
        WHERE segments.date DURING LAST_7_DAYS
    """
    
    # Last week for comparison
    query_last = """
        SELECT
            metrics.cost_micros,
            metrics.conversions
        FROM customer
        WHERE segments.date DURING LAST_14_DAYS
    """
    
    result = {
        "name": name,
        "this_week": {"cost": 0, "conv": 0, "clicks": 0, "impressions": 0},
    }
    
    try:
        response = ga_service.search(customer_id=customer_id, query=query_this)
        for row in response:
            result["this_week"]["cost"] = row.metrics.cost_micros / 1_000_000
            result["this_week"]["conv"] = row.metrics.conversions
            result["this_week"]["clicks"] = row.metrics.clicks
            result["this_week"]["impressions"] = row.metrics.impressions
    except Exception as e:
        result["error"] = str(e)
    
    return result

def get_top_campaigns(client, customer_id):
    """Get top performing campaigns."""
    ga_service = client.get_service("GoogleAdsService")
    
    query = """
        SELECT
            campaign.name,
            campaign.status,
            metrics.cost_micros,
            metrics.conversions,
            metrics.cost_per_conversion
        FROM campaign
        WHERE segments.date DURING LAST_7_DAYS
          AND campaign.status = 'ENABLED'
        ORDER BY metrics.conversions DESC
        LIMIT 5
    """
    
    campaigns = []
    try:
        response = ga_service.search(customer_id=customer_id, query=query)
        for row in response:
            cost = row.metrics.cost_micros / 1_000_000
            conv = row.metrics.conversions
            if conv > 0:
                campaigns.append({
                    "name": row.campaign.name[:30],
                    "cost": cost,
                    "conv": conv,
                    "cpa": cost / conv if conv > 0 else 0
                })
    except:
        pass
    
    return campaigns

def main():
    client = GoogleAdsClient.load_from_storage("/Users/dominiquezhoumacmini/.google-ads.yaml")
    
    print(f"📈 **Google Ads Weekly Report**")
    print(f"Week ending {datetime.now().strftime('%Y-%m-%d')}\n")
    print("─" * 40)
    
    total_cost = 0
    total_conv = 0
    
    for key, (name, cid) in ACCOUNTS.items():
        perf = get_account_performance(client, name, cid)
        
        cost = perf["this_week"]["cost"]
        conv = perf["this_week"]["conv"]
        cpa = cost / conv if conv > 0 else 0
        
        total_cost += cost
        total_conv += conv
        
        print(f"\n**{name}**")
        print(f"  💰 Spend: ${cost:,.0f}")
        print(f"  🎯 Conversions: {conv:.0f}")
        print(f"  📊 CPA: ${cpa:.0f}")
        
        # Top campaigns
        campaigns = get_top_campaigns(client, cid)
        if campaigns:
            print(f"  🏆 Top campaigns:")
            for c in campaigns[:3]:
                print(f"     • {c['name']}: {c['conv']:.0f} conv @ ${c['cpa']:.0f}")
    
    print("\n" + "─" * 40)
    avg_cpa = total_cost / total_conv if total_conv > 0 else 0
    print(f"\n**📊 TOTAL (All Accounts)**")
    print(f"  💰 Spend: ${total_cost:,.0f}")
    print(f"  🎯 Conversions: {total_conv:.0f}")
    print(f"  📊 Avg CPA: ${avg_cpa:.0f}")

if __name__ == "__main__":
    main()
