#!/usr/bin/env python3
"""
Daily Google Ads Health Check
Run via cron to detect issues and alert via stdout (Clawdbot picks up).
"""

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"),
}

# Thresholds
WASTE_THRESHOLD = 50  # Alert if keyword spent $50+ with 0 conversions
HIGH_CPA_MULTIPLIER = 2  # Alert if CPA > 2x average

def check_account(client, name, customer_id):
    """Run health checks on an account."""
    ga_service = client.get_service("GoogleAdsService")
    issues = []
    
    # 1. Check for zero-conversion keywords with high spend
    query = """
        SELECT
            ad_group_criterion.keyword.text,
            campaign.name,
            metrics.cost_micros,
            metrics.conversions
        FROM keyword_view
        WHERE segments.date DURING LAST_7_DAYS
          AND metrics.conversions = 0
          AND metrics.cost_micros > 0
        ORDER BY metrics.cost_micros DESC
        LIMIT 20
    """
    
    try:
        response = ga_service.search(customer_id=customer_id, query=query)
        for row in response:
            cost = row.metrics.cost_micros / 1_000_000
            if cost >= WASTE_THRESHOLD:
                issues.append({
                    "type": "WASTE",
                    "severity": "HIGH" if cost > 100 else "MEDIUM",
                    "message": f"💸 Keyword '{row.ad_group_criterion.keyword.text}' spent ${cost:.0f} with 0 conversions (7d)",
                    "campaign": row.campaign.name,
                    "cost": cost,
                })
    except Exception as e:
        issues.append({"type": "ERROR", "message": f"Failed to check keywords: {e}"})
    
    # 2. Check campaign performance
    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'
          AND metrics.cost_micros > 0
    """
    
    try:
        response = ga_service.search(customer_id=customer_id, query=query)
        
        total_cost = 0
        total_conv = 0
        campaigns = []
        
        for row in response:
            cost = row.metrics.cost_micros / 1_000_000
            conv = row.metrics.conversions
            total_cost += cost
            total_conv += conv
            campaigns.append({
                "name": row.campaign.name,
                "cost": cost,
                "conv": conv,
                "cpa": cost / conv if conv > 0 else float('inf')
            })
        
        avg_cpa = total_cost / total_conv if total_conv > 0 else 0
        
        # Check for high CPA campaigns
        for c in campaigns:
            if c["cpa"] > avg_cpa * HIGH_CPA_MULTIPLIER and c["cost"] > 100:
                issues.append({
                    "type": "HIGH_CPA",
                    "severity": "MEDIUM",
                    "message": f"⚠️ Campaign '{c['name']}' CPA ${c['cpa']:.0f} is {c['cpa']/avg_cpa:.1f}x above average (${avg_cpa:.0f})",
                    "campaign": c["name"],
                })
                
    except Exception as e:
        issues.append({"type": "ERROR", "message": f"Failed to check campaigns: {e}"})
    
    return issues

def main():
    client = GoogleAdsClient.load_from_storage("/Users/dominiquezhoumacmini/.google-ads.yaml")
    
    all_issues = []
    account_summaries = []
    
    for key, (name, cid) in ACCOUNTS.items():
        issues = check_account(client, name, cid)
        for issue in issues:
            issue["account"] = name
        all_issues.extend(issues)
        
        # Get quick summary
        try:
            ga_service = client.get_service("GoogleAdsService")
            query = """
                SELECT metrics.cost_micros, metrics.conversions
                FROM customer
                WHERE segments.date DURING LAST_7_DAYS
            """
            response = ga_service.search(customer_id=cid, query=query)
            for row in response:
                cost = row.metrics.cost_micros / 1_000_000
                conv = row.metrics.conversions
                account_summaries.append(f"  • {name}: ${cost:,.0f} | {conv:.0f} conv")
        except:
            pass
    
    # Output report
    print(f"📊 **Google Ads Daily Check** — {datetime.now().strftime('%Y-%m-%d')}\n")
    
    if account_summaries:
        print("**Last 7 Days:**")
        for s in account_summaries:
            print(s)
        print()
    
    if all_issues:
        high_issues = [i for i in all_issues if i.get("severity") == "HIGH"]
        med_issues = [i for i in all_issues if i.get("severity") == "MEDIUM"]
        
        if high_issues:
            print(f"🚨 **{len(high_issues)} High Priority Issues:**")
            for i in high_issues:
                print(f"  {i['message']}")
            print()
        
        if med_issues:
            print(f"⚠️ **{len(med_issues)} Medium Priority Issues:**")
            for i in med_issues[:5]:  # Limit to 5
                print(f"  {i['message']}")
            print()
    else:
        print("✅ No issues detected. Accounts healthy!")

if __name__ == "__main__":
    main()
