#!/usr/bin/env python3
"""Detailed Google Ads report with correct date handling."""

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

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

def get_campaigns(client, customer_id, name):
    """Campaign performance last 30 days."""
    ga_service = client.get_service("GoogleAdsService")
    
    query = """
        SELECT
            campaign.id, campaign.name, campaign.status,
            campaign.bidding_strategy_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{'='*80}")
    print(f"📈 CAMPAIGNS: {name}")
    print(f"{'='*80}\n")
    
    try:
        response = ga_service.search(customer_id=customer_id, query=query)
        
        total_cost = 0
        total_conv = 0
        
        print(f"{'Campaign':<40} {'Bidding':<15} {'Cost':>10} {'Conv':>6} {'CPA':>8}")
        print("-" * 85)
        
        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
            bidding = row.campaign.bidding_strategy_type.name[:15]
            
            if cost > 0:
                total_cost += cost
                total_conv += conv
                print(f"{row.campaign.name[:40]:<40} {bidding:<15} ${cost:>9,.0f} {conv:>5.0f} ${cpa:>7.0f}")
        
        print("-" * 85)
        avg_cpa = total_cost / total_conv if total_conv > 0 else 0
        print(f"{'TOTAL':<40} {'':<15} ${total_cost:>9,.0f} {total_conv:>5.0f} ${avg_cpa:>7.0f}")
        
    except Exception as e:
        print(f"Error: {e}")

def get_keywords(client, customer_id, name):
    """Top keywords by spend."""
    ga_service = client.get_service("GoogleAdsService")
    
    query = """
        SELECT
            ad_group_criterion.keyword.text,
            ad_group_criterion.keyword.match_type,
            campaign.name,
            metrics.cost_micros, metrics.conversions, metrics.clicks
        FROM keyword_view
        WHERE segments.date DURING LAST_30_DAYS
          AND metrics.cost_micros > 0
        ORDER BY metrics.cost_micros DESC
        LIMIT 50
    """
    
    print(f"\n{'='*80}")
    print(f"🔑 TOP KEYWORDS: {name}")
    print(f"{'='*80}\n")
    
    zero_conv_cost = 0
    
    try:
        response = ga_service.search(customer_id=customer_id, query=query)
        
        print(f"{'Keyword':<30} {'Campaign':<25} {'Cost':>10} {'Conv':>6} {'Flag'}")
        print("-" * 80)
        
        count = 0
        for row in response:
            cost = row.metrics.cost_micros / 1_000_000
            conv = row.metrics.conversions
            kw = row.ad_group_criterion.keyword.text[:30]
            camp = row.campaign.name[:25]
            
            flag = "⚠️ WASTE" if conv == 0 and cost > 50 else ""
            if conv == 0:
                zero_conv_cost += cost
            
            count += 1
            if count <= 25:
                print(f"{kw:<30} {camp:<25} ${cost:>9,.0f} {conv:>5.0f} {flag}")
        
        print(f"\n💰 Zero-conversion spend (30d): ${zero_conv_cost:,.0f}")
        
    except Exception as e:
        print(f"Error: {e}")

def get_change_details(client, customer_id, name):
    """Detailed change history."""
    ga_service = client.get_service("GoogleAdsService")
    
    query = """
        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
        FROM change_event
        WHERE change_event.change_date_time DURING LAST_30_DAYS
        ORDER BY change_event.change_date_time DESC
        LIMIT 100
    """
    
    print(f"\n{'='*80}")
    print(f"📝 RECENT CHANGES: {name}")
    print(f"{'='*80}\n")
    
    try:
        response = ga_service.search(customer_id=customer_id, query=query)
        
        print(f"{'Date':<12} {'User':<25} {'Type':<20} {'Campaign':<20}")
        print("-" * 80)
        
        for row in response:
            date = row.change_event.change_date_time[:10]
            user = row.change_event.user_email[:25]
            rtype = row.change_event.change_resource_type.name[:20]
            camp = (row.campaign.name or "")[:20]
            
            print(f"{date:<12} {user:<25} {rtype:<20} {camp:<20}")
        
    except Exception as e:
        print(f"Error: {e}")

def main():
    client = GoogleAdsClient.load_from_storage("/Users/dominiquezhoumacmini/.google-ads.yaml")
    
    for name, cid in ACCOUNTS.items():
        get_campaigns(client, cid, name)
        get_keywords(client, cid, name)
        get_change_details(client, cid, name)

if __name__ == "__main__":
    main()
