#!/usr/bin/env python3
"""Analyze agency change history from Google Ads CSV export."""

import csv
from collections import defaultdict
from datetime import datetime

def analyze_change_history(filepath):
    users = defaultdict(int)
    change_types = defaultdict(int)
    campaigns = defaultdict(int)
    monthly = defaultdict(int)
    
    with open(filepath, 'r', encoding='utf-8') as f:
        # Skip header rows
        lines = f.readlines()
        
        # Find the actual data start (after headers)
        data_start = 0
        for i, line in enumerate(lines):
            if line.startswith('"') and '@' in line:
                data_start = i
                break
        
        # Parse data
        for line in lines[data_start:]:
            if not line.strip() or ',' not in line:
                continue
                
            # Parse CSV properly
            try:
                parts = []
                in_quotes = False
                current = ""
                for char in line:
                    if char == '"':
                        in_quotes = not in_quotes
                    elif char == ',' and not in_quotes:
                        parts.append(current.strip().strip('"'))
                        current = ""
                    else:
                        current += char
                parts.append(current.strip().strip('"'))
                
                if len(parts) >= 4:
                    date_str = parts[0]
                    user = parts[1]
                    campaign = parts[2]
                    changes = parts[4] if len(parts) > 4 else ""
                    
                    # Count users
                    if '@' in user:
                        users[user] += 1
                    
                    # Count campaigns
                    if campaign:
                        campaigns[campaign] += 1
                    
                    # Parse change types
                    if changes:
                        change_line = changes.split('\n')[0]
                        for kw in ['budget amount', 'keyword', 'campaign paused', 'campaign active', 
                                   'Target ROAS', 'Asset group', 'ad changed', 'ad created', 'asset']:
                            if kw.lower() in change_line.lower():
                                change_types[kw] += 1
                                break
                        else:
                            change_types['other'] += 1
                    
                    # Parse month
                    if date_str:
                        try:
                            parts_date = date_str.split()
                            if len(parts_date) >= 3:
                                month_year = f"{parts_date[1]} {parts_date[2]}"
                                monthly[month_year] += 1
                        except:
                            pass
                            
            except Exception as e:
                continue
    
    return users, change_types, campaigns, monthly

def main():
    filepath = '/Users/dominiquezhoumacmini/clawd/data/google_ads_change_history_FR.csv'
    
    users, change_types, campaigns, monthly = analyze_change_history(filepath)
    
    print("=" * 60)
    print("📊 AGENCY CHANGE HISTORY ANALYSIS (FR/EU Account)")
    print("=" * 60)
    
    print("\n👤 CHANGES BY USER:")
    for user, count in sorted(users.items(), key=lambda x: -x[1])[:10]:
        print(f"   {user}: {count}")
    
    print("\n🔧 CHANGE TYPES:")
    for ctype, count in sorted(change_types.items(), key=lambda x: -x[1])[:15]:
        print(f"   {ctype}: {count}")
    
    print("\n🎯 TOP CAMPAIGNS (by changes):")
    for campaign, count in sorted(campaigns.items(), key=lambda x: -x[1])[:10]:
        print(f"   {campaign[:50]}: {count}")
    
    print("\n📅 CHANGES BY MONTH:")
    for month, count in sorted(monthly.items()):
        print(f"   {month}: {count}")
    
    # Calculate agency stats
    total_agency = users.get('stefan@ceos.fr', 0)
    total_you = users.get('contact@zede-paris.com', 0)
    total = sum(users.values())
    
    print("\n" + "=" * 60)
    print("📈 SUMMARY:")
    print(f"   Total changes: {total}")
    print(f"   Agency (stefan@ceos.fr): {total_agency} ({total_agency/total*100:.1f}%)")
    print(f"   You (contact@zede-paris.com): {total_you} ({total_you/total*100:.1f}%)")
    print("=" * 60)

if __name__ == "__main__":
    main()
