#!/usr/bin/env python3
"""
Ghost Agency - AI Social Ads Manager (TikTok + Instagram + Facebook)
Automated social ads management: creative generation, targeting, retargeting, A/B testing
"""

import os
import json
import sqlite3
import hashlib
import time
import random
from pathlib import Path
from datetime import datetime, timedelta
from typing import Dict, List, Any

DB_FILE = Path("/home/ubuntu/GhostAgency") / "revenue_bots.db"
SOCIAL_ADS_DB = Path("/home/ubuntu/GhostAgency") / "ai_social_ads.db"

# ============================================================
# AI SOCIAL ADS MANAGER
# ============================================================

class AISocialAdsManager:
    def __init__(self):
        self.db_path = str(SOCIAL_ADS_DB)
        self.openrouter_api_key = os.getenv("OPENROUTER_API_KEY", "")
        self.tiktok_app_id = os.getenv("TIKTOK_APP_ID", "")
        self.tiktok_app_secret = os.getenv("TIKTOK_APP_SECRET", "")
        self.tiktok_access_token = os.getenv("TIKTOK_ACCESS_TOKEN", "")
        self.meta_app_id = os.getenv("META_APP_ID", "")
        self.meta_app_secret = os.getenv("META_APP_SECRET", "")
        self.meta_access_token = os.getenv("META_ACCESS_TOKEN", "")
        self.init_db()
    
    def init_db(self):
        conn = sqlite3.connect(self.db_path)
        c = conn.cursor()
        
        # Ad Accounts
        c.execute("""CREATE TABLE IF NOT EXISTS social_ad_accounts (
            id TEXT PRIMARY KEY,
            client_id TEXT NOT NULL,
            business_name TEXT,
            platform TEXT,  -- tiktok, instagram, facebook
            account_id TEXT,
            access_token TEXT,
            pixel_id TEXT,
            business_manager_id TEXT,
            currency TEXT DEFAULT 'EUR',
            timezone TEXT DEFAULT 'Europe/Rome',
            status TEXT DEFAULT 'active',
            created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP
        )""")
        
        # Campaigns
        c.execute("""CREATE TABLE IF NOT EXISTS social_campaigns (
            id TEXT PRIMARY KEY,
            account_id TEXT NOT NULL,
            client_id TEXT NOT NULL,
            platform TEXT,
            campaign_name TEXT,
            objective TEXT,  -- conversions, traffic, video_views, reach, engagement, lead_generation
            buying_type TEXT,  -- auction, reservation
            status TEXT DEFAULT 'draft',
            daily_budget REAL,
            lifetime_budget REAL,
            bid_strategy TEXT,  -- lowest_cost, cost_cap, bid_cap, target_cost
            bid_amount REAL,
            start_date DATE,
            end_date DATE,
            special_ad_categories TEXT,  -- JSON
            created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
            updated_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
            FOREIGN KEY (account_id) REFERENCES social_ad_accounts(id)
        )""")
        
        # Ad Sets
        c.execute("""CREATE TABLE IF NOT EXISTS social_ad_sets (
            id TEXT PRIMARY KEY,
            campaign_id TEXT NOT NULL,
            client_id TEXT NOT NULL,
            ad_set_name TEXT,
            status TEXT DEFAULT 'draft',
            daily_budget REAL,
            lifetime_budget REAL,
            bid_strategy TEXT,
            bid_amount REAL,
            optimization_goal TEXT,  -- conversions, link_clicks, landing_page_views, video_views
            billing_event TEXT,  -- impressions, link_clicks, video_views
            targeting TEXT,  -- JSON
            placement TEXT,  -- automatic, manual
            placements TEXT,  -- JSON array
            start_date DATE,
            end_date DATE,
            created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
            FOREIGN KEY (campaign_id) REFERENCES social_campaigns(id)
        )""")
        
        # Ads/Creatives
        c.execute("""CREATE TABLE IF NOT EXISTS social_ads (
            id TEXT PRIMARY KEY,
            ad_set_id TEXT NOT NULL,
            client_id TEXT NOT NULL,
            platform TEXT,
            ad_name TEXT,
            creative_type TEXT,  -- image, video, carousel, collection, story, reel
            primary_text TEXT,
            headline TEXT,
            description TEXT,
            call_to_action TEXT,
            media_urls TEXT,  -- JSON array
            video_url TEXT,
            thumbnail_url TEXT,
            destination_url TEXT,
            display_url TEXT,
            status TEXT DEFAULT 'draft',
            creative_id TEXT,
            created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
            FOREIGN KEY (ad_set_id) REFERENCES social_ad_sets(id)
        )""")
        
        # Creative Library
        c.execute("""CREATE TABLE IF NOT EXISTS creative_library (
            id TEXT PRIMARY KEY,
            client_id TEXT NOT NULL,
            platform TEXT,
            creative_type TEXT,
            concept TEXT,
            headline TEXT,
            primary_text TEXT,
            cta TEXT,
            media_prompt TEXT,
            media_url TEXT,
            video_script TEXT,
            hook TEXT,
            body TEXT,
            cta_text TEXT,
            performance_score REAL DEFAULT 0,
            times_used INTEGER DEFAULT 0,
            last_used TIMESTAMP,
            status TEXT DEFAULT 'draft',
            created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP
        )""")
        
        # Audiences
        c.execute("""CREATE TABLE IF NOT EXISTS social_audiences (
            id TEXT PRIMARY KEY,
            client_id TEXT NOT NULL,
            platform TEXT,
            audience_name TEXT,
            audience_type TEXT,  -- saved, custom, lookalike, broad
            source TEXT,  -- pixel, customer_list, engagement, website
            source_id TEXT,
            targeting_spec TEXT,  -- JSON
            location TEXT,
            age_min INTEGER,
            age_max INTEGER,
            genders TEXT,  -- JSON
            interests TEXT,  -- JSON
            behaviors TEXT,  -- JSON
            size_estimate INTEGER,
            status TEXT DEFAULT 'active',
            created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP
        )""")
        
        # Performance Metrics
        c.execute("""CREATE TABLE IF NOT EXISTS social_performance (
            id TEXT PRIMARY KEY,
            entity_id TEXT,
            entity_type TEXT,  -- campaign, ad_set, ad
            client_id TEXT NOT NULL,
            platform TEXT,
            date DATE,
            spend REAL DEFAULT 0,
            impressions INTEGER DEFAULT 0,
            clicks INTEGER DEFAULT 0,
            ctr REAL DEFAULT 0,
            cpc REAL DEFAULT 0,
            cpm REAL DEFAULT 0,
            conversions REAL DEFAULT 0,
            conversion_value REAL DEFAULT 0,
            cpa REAL DEFAULT 0,
            roas REAL DEFAULT 0,
            video_views INTEGER DEFAULT 0,
            video_play_25 INTEGER DEFAULT 0,
            video_play_50 INTEGER DEFAULT 0,
            video_play_75 INTEGER DEFAULT 0,
            video_play_100 INTEGER DEFAULT 0,
            engagement INTEGER DEFAULT 0,
            engagement_rate REAL DEFAULT 0,
            link_clicks INTEGER DEFAULT 0,
            landing_page_views INTEGER DEFAULT 0,
            leads INTEGER DEFAULT 0,
            cost_per_lead REAL DEFAULT 0,
            created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP
        )""")
        
        # A/B Tests
        c.execute("""CREATE TABLE IF NOT EXISTS social_ab_tests (
            id TEXT PRIMARY KEY,
            client_id TEXT NOT NULL,
            test_name TEXT,
            test_type TEXT,  -- creative, audience, placement, copy, hook, cta
            control_id TEXT,
            variant_ids TEXT,  -- JSON
            metric TEXT,  -- cpa, roas, ctr, cpl, cpm
            status TEXT DEFAULT 'running',
            confidence REAL DEFAULT 0.95,
            min_spend REAL DEFAULT 50,
            start_date DATE,
            end_date DATE,
            winner_id TEXT,
            results TEXT,
            created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP
        )""")
        
        # Creative Concepts
        c.execute("""CREATE TABLE IF NOT EXISTS creative_concepts (
            id TEXT PRIMARY KEY,
            category TEXT,
            platform TEXT,
            concept_name TEXT,
            hook_template TEXT,
            body_template TEXT,
            cta_templates TEXT,  -- JSON
            visual_prompt TEXT,
            video_script_template TEXT,
            music_style TEXT,
            trending_elements TEXT,  -- JSON
            best_for TEXT,  -- awareness, consideration, conversion
            created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP
        )""")
        
        # Influencer Campaigns
        c.execute("""CREATE TABLE IF NOT EXISTS influencer_campaigns (
            id TEXT PRIMARY KEY,
            client_id TEXT NOT NULL,
            campaign_name TEXT,
            platform TEXT,
            budget REAL,
            status TEXT DEFAULT 'planning',
            influencer_tier TEXT,  -- nano, micro, macro, mega
            target_reach INTEGER,
            target_engagement REAL,
            content_type TEXT,  -- post, story, reel, tiktok, live
            deliverables TEXT,  -- JSON
            tracking_links TEXT,  -- JSON
            start_date DATE,
            end_date DATE,
            created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP
        )""")
        
        # Influencers
        c.execute("""CREATE TABLE IF NOT EXISTS influencers (
            id TEXT PRIMARY KEY,
            platform TEXT,
            username TEXT,
            display_name TEXT,
            follower_count INTEGER,
            engagement_rate REAL,
            avg_views INTEGER,
            avg_likes INTEGER,
            avg_comments INTEGER,
            category TEXT,
            location TEXT,
            languages TEXT,  -- JSON
            audience_demographics TEXT,  -- JSON
            rates TEXT,  -- JSON: post, story, reel, tiktok
            contact_email TEXT,
            contact_phone TEXT,
            verified INTEGER DEFAULT 0,
            past_campaigns TEXT,  -- JSON
            status TEXT DEFAULT 'available',
            created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP
        )""")
        
        conn.commit()
        conn.close()
        
        # Initialize creative concepts
        self._init_creative_concepts()
    
    def _init_creative_concepts(self):
        """Initialize creative concept templates."""
        conn = sqlite3.connect(self.db_path)
        c = conn.cursor()
        
        # Check if already initialized
        c.execute("SELECT COUNT(*) FROM creative_concepts")
        if c.fetchone()[0] > 0:
            conn.close()
            return
        
        concepts = [
            # TIKTOK CONCEPTS
            {
                "category": "ristorante",
                "platform": "tiktok",
                "concept_name": "Behind the Scenes - Pasta Making",
                "hook_template": "POV: Come facciamo la pasta fresca ogni mattina �����",
                "body_template": "Niente macchine, solo mani esperte e ingredienti veri. {nome} a {location} �����",
                "cta_templates": json.dumps(["Vieni a provarla!", "Prenota il tuo tavolo", "Tagga chi la vuole mangiare"]),
                "visual_prompt": "Close-up hands making fresh pasta, flour dust, eggs, rolling pin, authentic Italian kitchen",
                "video_script_template": "0-3s: Hook - flour flying, eggs cracking\n3-10s: Process - kneading, rolling, cutting\n10-15s: Cooking - boiling, sauce tossing\n15-25s: Reveal - beautiful plated dish\n25-30s: CTA - location, booking info",
                "music_style": "Upbeat Italian instrumental",
                "trending_elements": json.dumps(["#pastamaking", "#italianfood", "#foodporn", "ASMR cooking sounds"]),
                "best_for": "awareness"
            },
            {
                "category": "pizzeria",
                "platform": "tiktok",
                "concept_name": "Pizza in 450°C Oven",
                "hook_template": "450 gradi in 90 secondi: la vera pizza napoletana �����",
                "body_template": "Impasto 24h, San Marzano DOP, Bufala Campana. Solo da {nome} a {location} �����",
                "cta_templates": json.dumps(["Ordina ora!", "Consegna in 20 min", "Vieni a vederla cuocere"]),
                "visual_prompt": "Pizza entering wood-fired oven, flames, bubbling mozzarella, 450°C thermometer",
                "video_script_template": "0-3s: Oven thermometer 450°C\n3-8s: Pizza sliding in\n8-15s: Bubbling, rotating\n15-20s: Perfect leopard spots\n20-25s: Slice pull\n25-30s: CTA + location",
                "music_style": "Fast-paced, satisfying ASMR",
                "trending_elements": json.dumps(["#pizzanapoletana", "#woodfired", "#pizzaporn", "oven sounds"]),
                "best_for": "awareness"
            },
            {
                "category": "gelateria",
                "platform": "tiktok",
                "concept_name": "Gelato Scoop ASMR",
                "hook_template": "Il suono del gelato perfetto ��������",
                "body_template": "Latte fresco, panna, zero coloranti. {nome} a {location} - gelato vero �����",
                "cta_templates": json.dumps(["Quale gusto scegli?", "Vieni ad assaggiarlo", "Nuovo gusto questa settimana"]),
                "visual_prompt": "Perfect gelato scoop, waffle cone, multiple flavors, natural lighting, slow motion drizzle",
                "video_script_template": "0-3s: Scoop entering container - satisfying sound\n3-10s: Multiple flavors, texture close-up\n10-20s: Cone assembly, drizzle\n20-25s: First bite reaction\n25-30s: CTA",
                "music_style": "Calm, satisfying ASMR",
                "trending_elements": json.dumps(["#gelatoartigianale", "#asmrfood", "#gelato", "scoop sound"]),
                "best_for": "awareness"
            },
            {
                "category": "caffetteria",
                "platform": "tiktok",
                "concept_name": "Latte Art Satisfying",
                "hook_template": "Quando il cappuccino è troppo bello per berlo ��������",
                "body_template": "100% Arabica, latte art fatta a mano. {nome} a {location} �����",
                "cta_templates": json.dumps(["Vieni a provarlo", "Impara da noi", "Il tuo cappuccino perfetto"]),
                "visual_prompt": "Latte art pouring, rosetta, tulip, swan designs, slow motion, morning light",
                "video_script_template": "0-3s: Milk steaming sound\n3-10s: Pouring latte art\n10-20s: Design reveal\n20-25s: Sip\n25-30s: CTA",
                "music_style": "Chill lo-fi coffee shop",
                "trending_elements": json.dumps(["#latteart", "#cappuccino", "#coffeelover", "pouring sounds"]),
                "best_for": "awareness"
            },
            {
                "category": "bar",
                "platform": "tiktok",
                "concept_name": "Cocktail Shaking ASMR",
                "hook_template": "Il suono dello shaker perfetto �����",
                "body_template": "Cocktail signature, ingredienti premium. {nome} a {location} - aperitivo level �����",
                "cta_templates": json.dumps(["Prenota il tuo tavolo", "Prova il nostro signature", "Happy hour 18-20"]),
                "visual_prompt": "Cocktail shaking, ice clinking, strain into glass, garnish, moody bar lighting",
                "video_script_template": "0-3s: Ice into shaker\n3-10s: Ingredients pour\n10-20s: Hard shake\n20-25s: Strain, garnish\n25-30s: Cheers + CTA",
                "music_style": "Jazz, sophisticated bar vibes",
                "trending_elements": json.dumps(["#cocktail", "#mixology", "#aperitivo", "shaker sounds"]),
                "best_for": "awareness"
            },
            {
                "category": "ristorante",
                "platform": "instagram",
                "concept_name": "Carousel - Menu Highlights",
                "hook_template": "Swipe per vedere i nostri piatti più amati ��������",
                "body_template": "Da {nome} a {location}: tradizione, qualità, passione. Quale provi per primo? �����",
                "cta_templates": json.dumps(["Prenota ora", "Vedi menu completo", "Ordinazione online"]),
                "visual_prompt": "Carousel: 1) Pasta carbonara 2) Risotto 3) Tiramisu 4) Wine pairing 5) Interior",
                "video_script_template": "",
                "music_style": "",
                "trending_elements": json.dumps(["#ristoranteparma", "#parmafood", "#foodporn", "carousel format"]),
                "best_for": "consideration"
            },
            {
                "category": "centro_estetico",
                "platform": "instagram",
                "concept_name": "Before/After Reel",
                "hook_template": "La trasformazione che non ti aspetti �������",
                "body_template": "Trattamento {trattamento} da {nome} a {location}. Risultati visibili dalla prima seduta �����",
                "cta_templates": json.dumps(["Prenota la tua consulenza", "Scopri i trattamenti", "Offerta prima volta"]),
                "visual_prompt": "Split screen before/after, facial treatment, glowing skin, relaxed atmosphere",
                "video_script_template": "0-3s: Before shot\n3-10s: Treatment process\n10-20s: After reveal\n20-25s: Client reaction\n25-30s: CTA + offer",
                "music_style": "Relaxing spa music",
                "trending_elements": json.dumps(["#skincare", "#beforeafter", "#estetista", "transformation"]),
                "best_for": "conversion"
            },
            {
                "category": "parrucchiere",
                "platform": "instagram",
                "concept_name": "Hair Transformation Reel",
                "hook_template": "Da 'così' a 'wow' in 60 secondi ��������",
                "body_template": "Nuovo taglio, nuovo colore, nuovo te! {nome} a {location} �����",
                "cta_templates": json.dumps(["Prenota il tuo cambio look", "Consulenza gratuita", "Vedi altri lavori"]),
                "visual_prompt": "Fast cuts: before -> washing -> cutting -> coloring -> styling -> final reveal",
                "video_script_template": "0-3s: Before\n3-15s: Process montage\n15-25s: Color processing\n25-30s: Final reveal\n30-35s: Client happy\n35-40s: CTA",
                "music_style": "Trending upbeat",
                "trending_elements": json.dumps(["#hairtransformation", "#parrucchiere", "#balayage", "transition trend"]),
                "best_for": "conversion"
            },
            {
                "category": "autofficina",
                "platform": "facebook",
                "concept_name": "Trust Building - Video Testimonial",
                "hook_template": "Perché i clienti scelgono {nome} per la loro auto �����",
                "body_template": "Onestà, competenza, prezzi chiari. {location} - da 20 anni al tuo servizio �����",
                "cta_templates": json.dumps(["Prenota il tagliando", "Richiedi preventivo", "Chiamaci ora"]),
                "visual_prompt": "Mechanic explaining repair, customer nodding, clean workshop, invoice transparency",
                "video_script_template": "0-3s: Customer testimonial\n3-15s: Workshop tour\n15-25s: Transparent pricing\n25-30s: CTA + phone",
                "music_style": "Professional, trustworthy",
                "trending_elements": json.dumps(["#meccanico", "#autofficina", "#fiducia", "testimonial"]),
                "best_for": "conversion"
            },
            {
                "category": "dentista",
                "platform": "facebook",
                "concept_name": "Educational - Dental Tips",
                "hook_template": "3 errori che fai lavando i denti (e come correggerli) �����",
                "body_template": "Studio {nome} a {location}: prevenzione prima di tutto. La tua salute orale ci sta a cuore �����",
                "cta_templates": json.dumps(["Prenota igiene", "Consulenza gratuita", "Scarica guida gratis"]),
                "visual_prompt": "Dentist demonstrating brushing technique, flossing, electric toothbrush, friendly",
                "video_script_template": "0-3s: Hook - common mistake\n3-15s: Demo correct technique\n15-25s: Pro tip\n25-30s: CTA + offer",
                "music_style": "Clean, educational",
                "trending_elements": json.dumps(["#igieneorale", "#dentista", "#consigli", "educational"]),
                "best_for": "consideration"
            }
        ]
        
        for concept in concepts:
            cid = hashlib.md5(f"{concept['category']}{concept['platform']}{concept['concept_name']}".encode()).hexdigest()[:12]
            c.execute("""
                INSERT INTO creative_concepts
                (id, category, platform, concept_name, hook_template, body_template, cta_templates,
                 visual_prompt, video_script_template, music_style, trending_elements, best_for)
                VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
            """, (
                cid, concept["category"], concept["platform"], concept["concept_name"],
                concept["hook_template"], concept["body_template"], concept["cta_templates"],
                concept["visual_prompt"], concept["video_script_template"], concept["music_style"],
                concept["trending_elements"], concept["best_for"]
            ))
        
        conn.commit()
        conn.close()
    
    def register_client(self, client_data: Dict) -> str:
        """Register a client for social ads management."""
        client_id = client_data.get("client_id", hashlib.md5(f"{client_data.get('business_name', '')}{time.time()}".encode()).hexdigest()[:12])
        
        conn = sqlite3.connect(self.db_path)
        c = conn.cursor()
        
        # Create default package
        package_id = hashlib.md5(f"social_pkg_{client_id}{time.time()}".encode()).hexdigest()[:12]
        c.execute("""
            INSERT OR REPLACE INTO social_ad_accounts
            (id, client_id, business_name, platform, currency, timezone, status)
            VALUES (?, ?, ?, 'both', 'EUR', 'Europe/Rome', 'active')
        """, (package_id, client_id, client_data.get("business_name", "")))
        
        conn.commit()
        conn.close()
        return client_id
    
    def get_creative_concepts(self, category: str, platform: str = None) -> List[Dict]:
        """Get creative concepts for a category/platform."""
        conn = sqlite3.connect(self.db_path)
        c = conn.cursor()
        
        query = "SELECT * FROM creative_concepts WHERE category = ?"
        params = [category.lower()]
        
        if platform:
            query += " AND platform = ?"
            params.append(platform)
        
        c.execute(query, params)
        concepts = c.fetchall()
        conn.close()
        
        return [dict(zip(["id", "category", "platform", "concept_name", "hook_template", "body_template",
                         "cta_templates", "visual_prompt", "video_script_template", "music_style",
                         "trending_elements", "best_for", "created_at"], c)) for c in concepts]
    
    def generate_creatives_for_client(self, client_data: Dict) -> List[Dict]:
        """Generate social ad creatives for a client."""
        client_id = client_data.get("client_id", "")
        business_name = client_data.get("business_name", "")
        category = client_data.get("category", "")
        location = client_data.get("location", "Parma")
        
        creatives = []
        
        # Get concepts for this category
        concepts = self.get_creative_concepts(category)
        
        if not concepts:
            # Fallback to generic
            concepts = self.get_creative_concepts("default")
        
        platforms = ["tiktok", "instagram", "facebook"]
        
        for concept in concepts[:4]:  # Top 4 concepts
            platform = concept.get("platform", "tiktok")
            
            # Generate creative variations
            hook = concept["hook_template"].format(nome=business_name, location=location, category=category)
            body = concept["body_template"].format(nome=business_name, location=location, category=category, trattamento="viso illuminante")
            cta_options = json.loads(concept["cta_templates"])
            
            for i, cta in enumerate(cta_options[:2]):
                creative_id = hashlib.md5(f"creative_{client_id}{concept['concept_name']}{cta}{time.time()}".encode()).hexdigest()[:12]
                
                creative = {
                    "id": creative_id,
                    "client_id": client_id,
                    "platform": platform,
                    "concept_name": concept["concept_name"],
                    "creative_type": "video" if platform == "tiktok" else "reel" if platform == "instagram" else "video",
                    "hook": hook,
                    "primary_text": f"{hook}\n\n{body}\n\n{cta}",
                    "headline": hook[:40],
                    "call_to_action": cta,
                    "visual_prompt": concept["visual_prompt"].format(nome=business_name, location=location),
                    "video_script": concept["video_script_template"].format(nome=business_name, location=location),
                    "music_style": concept["music_style"],
                    "trending_hashtags": json.loads(concept["trending_elements"]),
                    "best_for": concept["best_for"],
                    "status": "draft"
                }
                creatives.append(creative)
                
                # Save to library
                self._save_creative(creative)
        
        return creatives
    
    def _save_creative(self, creative: Dict):
        """Save creative to library."""
        conn = sqlite3.connect(self.db_path)
        c = conn.cursor()
        c.execute("""
            INSERT INTO creative_library
            (id, client_id, platform, creative_type, concept, headline, primary_text, cta,
             media_prompt, video_script, hook, body, cta_text, status)
            VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, 'draft')
        """, (
            creative["id"],
            creative["client_id"],
            creative["platform"],
            creative["creative_type"],
            creative["concept_name"],
            creative["headline"],
            creative["primary_text"],
            creative["call_to_action"],
            creative["visual_prompt"],
            creative["video_script"],
            creative["hook"],
            creative["primary_text"].split("\n\n")[1] if "\n\n" in creative["primary_text"] else "",
            creative["call_to_action"]
        ))
        conn.commit()
        conn.close()
    
    def generate_audiences_for_client(self, client_data: Dict) -> List[Dict]:
        """Generate audience targeting for a client."""
        client_id = client_data.get("client_id", "")
        business_name = client_data.get("business_name", "")
        category = client_data.get("category", "")
        location = client_data.get("location", "Parma")
        
        audiences = []
        
        # Interest-based audiences by category
        interest_map = {
            "ristorante": ["Cucina italiana", "Ristoranti", "Cibo e bevande", "Cena romantica", "Pranzo", "Gastronomia", "Vino", "Foodie"],
            "pizzeria": ["Pizza", "Cucina napoletana", "Cibo da asporto", "Ristoranti italiani", "Mozzarella", "Pomodoro"],
            "gelateria": ["Gelato", "Dolci", "Dessert", "Gelateria artigianale", "Frutta", "Cono gelato"],
            "caffetteria": ["Caffè", "Cappuccino", "Colazione", "Specialty coffee", "Latte art", "Barista", "Caffetteria"],
            "bar": ["Cocktail", "Aperitivo", "Vita notturna", "Bar", "Happy hour", "Mixology", "Drink"],
            "parrucchiere": ["Parrucchiere", "Taglio capelli", "Colore capelli", "Acconciature", "Bellezza", "Hairstyle", "Balayage"],
            "centro_estetico": ["Estetica", "Trattamenti viso", "Massaggi", "Epilazione", "Manicure", "Pedicure", "Benessere", "Spa", "Skincare"],
            "autofficina": ["Auto", "Manutenzione auto", "Riparazione auto", "Meccanico", "Gomme", "Tagliando", "Revisione"],
            "dentista": ["Dentista", "Igiene orale", "Sbiancamento denti", "Ortodonzia", "Implantologia", "Salute dentale"]
        }
        
        interests = interest_map.get(category.lower(), ["Piccole imprese", "Servizi locali", "Shopping locale"])
        
        # Platform-specific audience configs
        platform_configs = {
            "tiktok": {
                "broad": {"name": f"Broad - {location} 18-55", "type": "broad", "location": location, "age_min": 18, "age_max": 55},
                "interest": {"name": f"Interest - {category} - {location}", "type": "interest", "location": location, "age_min": 18, "age_max": 55, "interests": interests},
                "lookalike": {"name": f"Lookalike 1% - Clienti - {location}", "type": "lookalike", "source": "pixel_purchasers", "location": location, "percentage": 1},
                "retargeting": {"name": f"Retargeting - Video Viewers 7d - {location}", "type": "custom", "source": "video_viewers_7d", "location": location}
            },
            "instagram": {
                "broad": {"name": f"Broad - {location} 22-50", "type": "broad", "location": location, "age_min": 22, "age_max": 50},
                "interest": {"name": f"Interest - {category} - {location}", "type": "interest", "location": location, "age_min": 22, "age_max": 50, "interests": interests},
                "engagement": {"name": f"Engagement - Profile Visitors 30d - {location}", "type": "custom", "source": "ig_profile_visitors_30d", "location": location},
                "lookalike": {"name": f"Lookalike 1% - Purchasers - {location}", "type": "lookalike", "source": "pixel_purchasers", "location": location, "percentage": 1}
            },
            "facebook": {
                "broad": {"name": f"Broad - {location} 25-60", "type": "broad", "location": location, "age_min": 25, "age_max": 60},
                "interest": {"name": f"Interest - {category} - {location}", "type": "interest", "location": location, "age_min": 25, "age_max": 60, "interests": interests},
                "lookalike": {"name": f"Lookalike 1% - Leads - {location}", "type": "lookalike", "source": "pixel_leads", "location": location, "percentage": 1},
                "retargeting": {"name": f"Retargeting - Website 30d - {location}", "type": "custom", "source": "website_visitors_30d", "location": location}
            }
        }
        
        for platform in ["tiktok", "instagram", "facebook"]:
            configs = platform_configs[platform]
            for aud_type, config in configs.items():
                aud_id = hashlib.md5(f"aud_{client_id}{platform}{aud_type}{time.time()}".encode()).hexdigest()[:12]
                config["id"] = aud_id
                config["client_id"] = client_id
                config["platform"] = platform
                config["status"] = "active"
                audiences.append(config)
                
                # Save to DB
                self._save_audience(config)
        
        return audiences
    
    def _save_audience(self, audience: Dict):
        """Save audience to DB."""
        conn = sqlite3.connect(self.db_path)
        c = conn.cursor()
        c.execute("""
            INSERT INTO social_audiences
            (id, client_id, platform, audience_name, audience_type, targeting_spec, location,
             age_min, age_max, interests, status)
            VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
        """, (
            audience["id"],
            audience["client_id"],
            audience["platform"],
            audience["name"],
            audience["type"],
            json.dumps({k: v for k, v in audience.items() if k not in ["id", "client_id", "platform", "name", "type", "location"]}),
            audience.get("location", ""),
            audience.get("age_min", 18),
            audience.get("age_max", 55),
            json.dumps(audience.get("interests", [])),
            audience.get("status", "active")
        ))
        conn.commit()
        conn.close()

# ============================================================
# EXECUTION
# ============================================================

def run_ai_social_ads_manager():
    """Run AI Social Ads Manager for all active clients."""
    print(f"\n{'='*60}")
    print(f" AI SOCIAL ADS MANAGER - TIKTOK + INSTAGRAM + FACEBOOK")
    print(f"{'='*60}\n")
    
    manager = AISocialAdsManager()
    
    # Get clients from leads broker
    conn = sqlite3.connect("/home/ubuntu/GhostAgency/lead_broker.db")
    c = conn.cursor()
    c.execute("""
        SELECT id, nome, categoria, citta, indirizzo 
        FROM leads_inventory 
        WHERE venduto = 0 AND email IS NOT NULL AND email != ''
        LIMIT 10
    """)
    leads = c.fetchall()
    conn.close()
    
    if not leads:
        print("[!] No leads with email found")
        return
    
    print(f"[*] Setting up social ads campaigns for {len(leads)} leads...")
    
    total_creatives = 0
    total_audiences = 0
    
    for lead in leads:
        lead_id, nome, categoria, citta, indirizzo = lead
        
        client_data = {
            "client_id": lead_id,
            "business_name": nome,
            "category": categoria,
            "location": citta,
            "address": indirizzo
        }
        
        # Register client
        manager.register_client(client_data)
        
        # Generate creatives
        creatives = manager.generate_creatives_for_client(client_data)
        total_creatives += len(creatives)
        
        # Generate audiences
        audiences = manager.generate_audiences_for_client(client_data)
        total_audiences += len(audiences)
        
        print(f"   [+] {nome} ({categoria}) - {len(creatives)} creatives, {len(audiences)} audiences")
    
    print(f"\n[+] AI Social Ads Manager setup complete")
    print(f"[+] Total creatives generated: {total_creatives}")
    print(f"[+] Total audiences created: {total_audiences}")
    print(f"[+] Creative library populated with trending concepts")
    print(f"[+] Next: Connect TikTok Ads API + Meta Marketing API for live deployment")

if __name__ == "__main__":
    run_ai_social_ads_manager()