#!/usr/bin/env python3
"""
Ghost Agency - Revenue Streams v4 (Extended)
Even more automated revenue streams - targeting €300k+ MRR potential
"""

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

LEADS_DIR = Path("/home/ubuntu/GhostAgency")
DB_FILE = Path("/home/ubuntu/GhostAgency") / "revenue_bots.db"
BROKER_DB = Path("/home/ubuntu/GhostAgency") / "lead_broker.db"

# ============================================================
# EXTENDED REVENUE STREAMS v4
# ============================================================

EXTENDED_STREAMS_V4 = {
    # === AI MARKETING AT SCALE ===
    "ai_local_ad_manager": {
        "name": "AI Gestione Ads Locali (Google/Meta)",
        "price_range": "15-20% ad spend + €200 setup",
        "frequency": "monthly",
        "automation_level": "high",
        "current_mrr": 0,
        "potential_mrr": 8000,
        "description": "Gestione automatica campagne Google Ads/Facebook Ads per locali: keyword research, ad copy, bidding, A/B test, reporting",
        "tools": ["Google Ads API", "Meta Marketing API", "OpenRouter per copy", "Keywords Planner", "Conversion tracking"],
        "target": "Ristoranti, palestre, dentisti, centri estetici, autonoleggi, hotel"
    },
    "ai_social_ad_manager": {
        "name": "AI Gestione Social Ads (TikTok/IG/FB)",
        "price_range": "15-20% ad spend + €150 setup",
        "frequency": "monthly",
        "automation_level": "high",
        "current_mrr": 0,
        "potential_mrr": 5000,
        "description": "Gestione automatica TikTok Ads, Instagram Ads, Facebook Ads per locali: creativi AI, targeting, retargeting",
        "tools": ["TikTok Ads API", "Meta Marketing API", "AI video generation (Runway/Sora)", "Creative testing"],
        "target": "Ristoranti, bar, gelaterie, palestre, centri estetici, locali notturni"
    },
    "ai_influencer_marketing_local": {
        "name": "AI Influencer Marketing Locale",
        "price_range": "€500-2000/campagna + 15% fee",
        "frequency": "per_campaign",
        "automation_level": "high",
        "current_mrr": 0,
        "potential_mrr": 4000,
        "description": "Identificazione automatica micro-influencer locali, outreach, gestione campagne, tracking ROI",
        "tools": ["Instagram/TikTok API", "Influencer DB", "AI content brief", "UTM tracking", "ROI calculator"],
        "target": "Ristoranti, gelaterie, centri estetici, palestre, locali notturni, hotel"
    },
    "ai_pr_distribution_local": {
        "name": "Distribuzione PR Locale Automatica",
        "price_range": "€200-500/comunicato + €100/mese",
        "frequency": "monthly",
        "automation_level": "high",
        "current_mrr": 0,
        "potential_mrr": 2000,
        "description": "Scrittura AI comunicati stampa, distribuzione automatica a media locali, giornalisti, blogger, portali",
        "tools": ["Media database API", "AI press release writer", "Email automation", "Coverage tracking"],
        "target": "Nuove aperture, eventi, lanci menu, premi, certificazioni, espansioni"
    },

    # === LOCAL BUSINESS INTELLIGENCE ===
    "local_competitor_pricing_monitor": {
        "name": "Monitoraggio Prezzi Competitor Automatico",
        "price_range": "€100-300/mese",
        "frequency": "monthly",
        "automation_level": "high",
        "current_mrr": 0,
        "potential_mrr": 3000,
        "description": "Monitoraggio automatico prezzi competitor (menu, listini, offerte), alert variazioni, report settimanali",
        "tools": ["Web scraping API", "Price comparison engine", "Alert engine", "PDF/Excel reports"],
        "target": "Ristoranti, pizzerie, gelaterie, bar, hotel, retail, palestre"
    },
    "local_market_research_reports": {
        "name": "Report Ricerca Mercato Locale (Subscription)",
        "price_range": "€100-300/mese",
        "frequency": "monthly",
        "automation_level": "high",
        "current_mrr": 0,
        "potential_mrr": 2500,
        "description": "Report mensili: nuove aperture, chiusure, trend categoria, demo grafici, opportunità per zona/categoria",
        "tools": ["Radar data", "Cadastral data", "Chamber of commerce API", "AI report generation"],
        "target": "Investitori, franchisor, catene, sviluppatori immobiliari, consulenti"
    },
    "local_business_valuation_tool": {
        "name": "Tool Valutazione Business Locali Automatico",
        "price_range": "€50-200/valutazione",
        "frequency": "per_valuation",
        "automation_level": "high",
        "current_mrr": 0,
        "potential_mrr": 2000,
        "description": "Valutazione automatica business locali: DCF, multipli settore, asset, goodwill, location score",
        "tools": ["Financial modeling API", "Location scoring", "Sector multiples DB", "DCF engine", "PDF report generator"],
        "target": "Proprietari venditori, acquirenti, broker, banche, commercialisti, M&A advisors"
    },
    "local_business_credit_score": {
        "name": "Credit Scoring Business Locali Automatico",
        "price_range": "€30-100/report",
        "frequency": "per_report",
        "automation_level": "high",
        "current_mrr": 0,
        "potential_mrr": 1500,
        "description": "Credit score automatico per business locali: bilanci, pagamenti, recensioni, location, settore, rischio",
        "tools": ["Cerved/CRIF API", "Bilanci depositati", "Payment behavior", "Review sentiment", "Location risk"],
        "target": "Banche, finanziarie, fornitori, franchisor, landlord, assicurazioni"
    },

    # === FRANCHISE / CHAIN AUTOMATION ===
    "franchise_compliance_monitor": {
        "name": "Monitoraggio Conformità Franchising Automatico",
        "price_range": "€200-500/location/mese",
        "frequency": "monthly",
        "automation_level": "high",
        "current_mrr": 0,
        "potential_mrr": 8000,
        "description": "Audit automatici standard brand: menu, prezzi, arredi, uniformi, processi, mystery shopping, report",
        "tools": ["Checklist digitali", "Photo audit AI", "Mystery shopper network", "Brand guidelines", "Alert engine"],
        "target": "Franchisor food, fitness, beauty, retail, services (10+ locations)"
    },
    "franchise_lead_gen_automated": {
        "name": "Lead Gen Franchising Automatica",
        "price_range": "€200-500/lead qualificato",
        "frequency": "per_lead",
        "automation_level": "high",
        "current_mrr": 0,
        "potential_mrr": 6000,
        "description": "Lead gen automatica franchisee: LinkedIn Ads, FB Ads, landing pages, qualificazione, CRM, nurturing",
        "tools": ["LinkedIn Ads API", "Meta Ads API", "Landing page builder", "CRM", "Email automation", "Calendly"],
        "target": "Franchisor food, fitness, beauty, education, services, retail"
    },
    "multi_location_seo_manager": {
        "name": "Gestione SEO Multi-Location Automatica",
        "price_range": "€50-150/location/mese",
        "frequency": "monthly",
        "automation_level": "high",
        "current_mrr": 0,
        "potential_mrr": 5000,
        "description": "Gestione SEO per catene: GMB multi-location, local pages, citazioni, recensioni, schema, report per location",
        "tools": ["GMB API", "Local SEO tools", "Citation builder", "Review monitoring", "Schema generator", "Bulk reporting"],
        "target": "Catene ristoranti, palestre, retail, hotel, servizi, franchising"
    },
    "franchise_operations_audit": {
        "name": "Audit Operativo Franchising Automatico",
        "price_range": "€500-1500/audit",
        "frequency": "per_audit",
        "automation_level": "medium",
        "current_mrr": 0,
        "potential_mrr": 3000,
        "description": "Audit standard operativi: food safety, service speed, cleanliness, staff training, brand compliance, P&L",
        "tools": ["Checklist digitali", "Photo audit", "POS data analysis", "Staff survey", "Financial benchmarking"],
        "target": "Franchisor, master franchisee, private equity, banche finanziatrici"
    },

    # === VERTICAL SPECIFIC ===
    "restaurant_revenue_optimizer": {
        "name": "Ottimizzazione Ricavi Ristoranti (Revenue Management)",
        "price_range": "€300-800/mese",
        "frequency": "monthly",
        "automation_level": "high",
        "current_mrr": 0,
        "potential_mrr": 4000,
        "description": "Dynamic pricing, menu engineering, demand forecasting, table turnover optimization, waste reduction",
        "tools": ["POS API", "Reservation system API", "Demand forecasting ML", "Pricing engine", "Table management"],
        "target": "Ristoranti 50+ coperti, fine dining, catene, hotel restaurant"
    },
    "hotel_revenue_management": {
        "name": "Revenue Management Hotel Automatico",
        "price_range": "€200-500/camera/mese",
        "frequency": "monthly",
        "automation_level": "high",
        "current_mrr": 0,
        "potential_mrr": 6000,
        "description": "Dynamic pricing, channel management, demand forecasting, OTA optimization, package creation",
        "tools": ["PMS API", "Channel manager API", "RMS engine", "Competitor rate shopping", "Demand forecasting"],
        "target": "Hotel 20-200 camere, boutique hotel, aparthotel, resort"
    },
    "gym_retention_optimizer": {
        "name": "Ottimizzazione Retention Palestre Automatico",
        "price_range": "€100-300/mese",
        "frequency": "monthly",
        "automation_level": "high",
        "current_mrr": 0,
        "potential_mrr": 3000,
        "description": "Churn prediction, winback automation, engagement scoring, class optimization, personal trainer scheduling",
        "tools": ["Member management API", "Access control data", "ML churn model", "WhatsApp/Email automation", "Class booking"],
        "target": "Palestre, centri fitness, crossfit box, yoga studio, piscine"
    },
    "beauty_salon_optimizer": {
        "name": "Ottimizzazione Centri Estetici/Parrucchieri",
        "price_range": "€100-300/mese",
        "frequency": "monthly",
        "automation_level": "high",
        "current_mrr": 0,
        "potential_mrr": 3000,
        "description": "Ottimizzazione agenda, retail product sales, membership, retail cross-sell, staff utilization, no-show reduction",
        "tools": ["Booking API", "POS API", "Inventory management", "Client CRM", "Retail recommendation engine"],
        "target": "Centri estetici, parrucchieri, spa, nail bar, barbiere, make-up artist"
    },

    # === FINTECH / PAYMENTS ===
    "local_business_lending_marketplace": {
        "name": "Marketplace Prestiti Business Locali",
        "price_range": "2-4% per prestito facilitato",
        "frequency": "per_deal",
        "automation_level": "high",
        "current_mrr": 0,
        "potential_mrr": 5000,
        "description": "Matchmaking automatico tra business locali e lender (banche, fintech, crowdfunding): POS financing, equipment, working capital",
        "tools": ["Lender API (Younited, Soisy, Scalapay, Banca Sella)", "Credit scoring", "Document automation", "E-signature"],
        "target": "Nuovi ristoranti, ristrutturazioni, attrezzature, espansioni, cash flow"
    },
    "pos_financing_automation": {
        "name": "Finanziamento POS/Attrezzature Automatico",
        "price_range": "2-4% per finanziamento",
        "frequency": "per_deal",
        "automation_level": "high",
        "current_mrr": 0,
        "potential_mrr": 3000,
        "description": "Finanziamento automatico POS, registratori cassa, forni, frigoriferi, arredi, arredo esterno",
        "tools": ["API Younited/Soisy/Scalapay/Banca Sella", "Credit scoring", "Document automation", "E-signature"],
        "target": "Nuovi ristoranti, ristrutturazioni, nuove aperture, upgrade attrezzature"
    },
    "merchant_cash_advance_broker": {
        "name": "Broker Merchant Cash Advance Automatico",
        "price_range": "3-6% importo anticipato",
        "frequency": "per_deal",
        "automation_level": "high",
        "current_mrr": 0,
        "potential_mrr": 4000,
        "description": "MCA automatico per ristoranti/retail: anticipo su futuri incassi POS, rimborso % giornaliero",
        "tools": ["POS data API", "Revenue based financing API", "Risk engine", "Daily repayment tracking"],
        "target": "Ristoranti, retail, bar, gelaterie, stagionali, cash flow gaps"
    },

    # === PROPERTY / REAL ESTATE ===
    "commercial_lease_optimizer": {
        "name": "Ottimizzazione Affitti Commerciali Automatica",
        "price_range": "€500-2000/negoziazione",
        "frequency": "per_lease",
        "automation_level": "medium",
        "current_mrr": 0,
        "potential_mrr": 3000,
        "description": "Analisi canoni mercato, benchmark, negoziazione assistita, break clause, rent review, break clause optimizer",
        "tools": ["Market rent API", "Comparable analyzer", "Lease analyzer AI", "Negotiation templates", "Market reports"],
        "target": "Ristoranti, retail, uffici, palestre, nuovi contratti, rinnovi, subletting"
    },
    "location_intelligence_saas": {
        "name": "Location Intelligence SaaS per Catene",
        "price_range": "€500-2000/mese",
        "frequency": "monthly",
        "automation_level": "high",
        "current_mrr": 0,
        "potential_mrr": 8000,
        "description": "Site selection AI: footfall, demographics, competition, cannibalization, catchment area, sales forecasting",
        "tools": ["Mobile location data", "Demographics API", "POI data", "Cannibalization model", "Sales forecasting ML", "Map visualization"],
        "target": "Catene retail, food, fitness, hotel, fuel, EV charging, last mile"
    },
    "retail_site_selector": {
        "name": "Site Selector Retail Automatico",
        "price_range": "€1000-5000/analisi",
        "frequency": "per_analysis",
        "automation_level": "high",
        "current_mrr": 0,
        "potential_mrr": 3000,
        "description": "Analisi location retail: footfall, demographics, competition, accessibility, rent/sales ratio, success probability",
        "tools": ["Footfall data", "Demographics", "Competition mapping", "Rent data", "Sales forecasting", "ROI calculator"],
        "target": "Retail chains, food chains, fitness chains, franchisor, developers, REIT"
    },

    # === SUSTAINABILITY / ESG ===
    "food_waste_tracking_ai": {
        "name": "Tracking Spreco Alimentare AI + Certificazione",
        "price_range": "€150-400/mese",
        "frequency": "monthly",
        "automation_level": "high",
        "current_mrr": 0,
        "potential_mrr": 3000,
        "description": "Tracking spreco AI, previsione domanda, ottimizzazione ordini, certificazione zero waste, report ESG",
        "tools": ["POS + Inventory API", "Demand forecasting ML", "Waste tracking scales", "Certification API", "ESG reporting"],
        "target": "Ristoranti, hotel, catering, mense, bakery, supermercati, mense aziendali"
    },
    "sustainable_menu_optimizer": {
        "name": "Ottimizzazione Menu Sostenibile AI",
        "price_range": "€200-500/mese",
        "frequency": "monthly",
        "automation_level": "high",
        "current_mrr": 0,
        "potential_mrr": 2000,
        "description": "Ottimizzazione carbon footprint menu: ingredienti locali, stagionali, plant-based, carbon labeling, cost optimization",
        "tools": ["Recipe database", "Carbon footprint DB", "Supplier API", "Nutritional API", "Cost optimizer", "Menu engineering"],
        "target": "Ristoranti sostenibili, catene, hotel, catering, mense aziendali, scuole"
    },
    "esg_reporting_automation": {
        "name": "Automazione Reporting ESG per PMI",
        "price_range": "€200-600/mese",
        "frequency": "monthly",
        "automation_level": "high",
        "current_mrr": 0,
        "potential_mrr": 3000,
        "description": "Reporting ESG automatico: carbon footprint, diversity, governance, supply chain, CSRD ready, stakeholder reports",
        "tools": ["Energy API", "HR data", "Supply chain data", "GHG calculator", "Report generator", "Framework mapper (GRI/SASB/TCFD)"],
        "target": "PMI soggette CSRD, catene, fornitori grandi aziende, export, B2B"
    },

    # === EDUCATION / HR ===
    "hospitality_staffing_marketplace": {
        "name": "Marketplace Staffing Ospitalità Automatico",
        "price_range": "15-25% fee per assunzione",
        "frequency": "per_hire",
        "automation_level": "high",
        "current_mrr": 0,
        "potential_mrr": 5000,
        "description": "Marketplace staffing stagionale/part-time: camerieri, cuochi, baristi, receptionist, pulizie, matching AI",
        "tools": ["ATS", "Candidate matching AI", "Skill verification", "Shift scheduling", "Payroll integration", "Compliance"],
        "target": "Hotel, ristoranti, catering, eventi, stagionali, catene, agenzie interinali"
    },
    "hospitality_training_automation": {
        "name": "Formazione Ospitalità Automatica (LMS + AI)",
        "price_range": "€15-30/dipendente/mese",
        "frequency": "monthly",
        "automation_level": "high",
        "current_mrr": 0,
        "potential_mrr": 4000,
        "description": "Formazione continua: HACCP, servizio, vendita, inglese, soft skills, compliance, certificati automatici",
        "tools": ["LMS whitelabel", "Video AI generation", "Quiz/certificati auto", "Tracking completamento", "Report manager", "Multi-language"],
        "target": "Hotel, ristoranti, catene, crociere, villaggi turistici, catering, mense"
    },

    # === TECH / DEV TOOLS ===
    "local_business_api_marketplace": {
        "name": "API Marketplace Dati Business Locali",
        "price_range": "Freemium + €0.10-1.00/call",
        "frequency": "monthly",
        "automation_level": "high",
        "current_mrr": 0,
        "potential_mrr": 5000,
        "description": "API per: lead gen, email validation, business data, SEO audit, review monitoring, GMB data, financial data",
        "tools": ["API Gateway", "Rate limiting", "Billing/Stripe", "Documentation", "SDKs", "Webhooks", "GraphQL/REST"],
        "target": "Sviluppatori, SaaS, agenzie tech, no-code builders, data companies, AI companies"
    },
    "local_business_data_licensing": {
        "name": "Licensing Dati Business Locali (Bulk)",
        "price_range": "€0.50-2.00/record",
        "frequency": "per_batch",
        "automation_level": "high",
        "current_mrr": 0,
        "potential_mrr": 5000,
        "description": "Vendita bulk dati business locali: NAP, categoria, recensioni, orari, foto, social, finanziari, proprietà",
        "tools": ["Data warehouse", "ETL pipelines", "Data quality", "Delivery (S3/SFTP/API)", "Licensing engine", "Compliance"],
        "target": "Data companies, AI training, mapping companies, marketing platforms, lead gen companies, researchers"
    },
    "white_label_local_seo_tool": {
        "name": "Tool SEO Locale Whitelabel per Agenzie",
        "price_range": "€99-499/mese per agenzia",
        "frequency": "monthly",
        "automation_level": "high",
        "current_mrr": 0,
        "potential_mrr": 10000,
        "description": "Tool SEO locale completo whitelabel: rank tracking, GMB audit, citation audit, competitor analysis, reporting white-label",
        "tools": ["Multi-tenant architecture", "Custom domains", "White-label dashboard", "API", "Client portal", "Billing"],
        "target": "Agenzie SEO, freelancer, web agency, marketing agency, consulenti, software house"
    },

    # === EMERGING TECH ===
    "ar_menu_experience": {
        "name": "Menu AR / Esperienza Realtà Aumentata",
        "price_range": "€500-2000 setup + €50-150/mese",
        "frequency": "monthly",
        "automation_level": "medium",
        "current_mrr": 0,
        "potential_mrr": 2000,
        "description": "Menu AR: piatti in 3D, info allergeni, pairing vino, traduzione, nutritional info, ordering integration",
        "tools": ["ARCore/ARKit", "WebAR", "3D food modeling", "POS integration", "QR codes", "Analytics"],
        "target": "Ristoranti premium, hotel, catene innovative, esperienziali, tourist areas"
    },
    "voice_ordering_assistant": {
        "name": "Assistente Ordinazione Vocale (Phone/Drive-thru)",
        "price_range": "€200-500/mese + setup",
        "frequency": "monthly",
        "automation_level": "high",
        "current_mrr": 0,
        "potential_mrr": 3000,
        "description": "Voice AI per ordinazioni telefoniche/drive-thru: NLU, menu navigation, upsell, payment, POS integration",
        "tools": ["ASR/TTS", "NLU", "Menu knowledge base", "POS integration", "Payment gateway", "Call recording"],
        "target": "Pizzerie, fast food, catene, drive-thru, takeaway, ghost kitchen"
    },
    "ai_phone_receptionist": {
        "name": "Ricezionista Telefonico AI per Locali",
        "price_range": "€100-300/mese",
        "frequency": "monthly",
        "automation_level": "high",
        "current_mrr": 0,
        "potential_mrr": 4000,
        "description": "AI risponde telefono: prenotazioni, FAQ, ordini takeaway, info orari/menu, transfer umano, CRM integration",
        "tools": ["ASR/TTS", "LLM", "Calendar API", "POS API", "CRM", "Call recording", "Analytics", "Multi-language"],
        "target": "Ristoranti, hotel, centri estetici, palestre, dentisti, studi medici, uffici"
    },

    # === DATA MONETIZATION ===
    "foot_traffic_data_licensing": {
        "name": "Licensing Dati Footfall (Bulk/API)",
        "price_range": "€500-5000/mese",
        "frequency": "monthly",
        "automation_level": "high",
        "current_mrr": 0,
        "potential_mrr": 5000,
        "description": "Vendita dati footfall anonimizzati: heatmap, dwell time, cross-visitation, demographics, catchment area",
        "tools": ["Mobile location data", "Aggregation engine", "Privacy compliance", "API/S3 delivery", "Visualization"],
        "target": "Retail REIT, city planners, advertisers, retailers, investors, researchers, city councils"
    },
    "local_search_trends_api": {
        "name": "API Trend Ricerca Locale (Google Trends Local)",
        "price_range": "€100-500/mese",
        "frequency": "monthly",
        "automation_level": "high",
        "current_mrr": 0,
        "potential_mrr": 2000,
        "description": "API trend ricerca locale: 'pizzeria vicino a me', 'ristorante aperto ora', 'gelateria aperta domenica', per zona/categoria",
        "tools": ["Google Trends API", "Search volume API", "Geo-trends", "Category trends", "Real-time alerts"],
        "target": "SEO agencies, marketing platforms, chains, investors, media, franchisor, ad agencies"
    },

    # === AUTOMATION INFRASTRUCTURE ===
    "business_automation_platform_whitelabel": {
        "name": "Piattaforma Automazione Business Whitelabel",
        "price_range": "€299-1999/mese per partner",
        "frequency": "monthly",
        "automation_level": "high",
        "current_mrr": 0,
        "potential_mrr": 20000,
        "description": "Piattaforma completa automazione business whitelabel: CRM, email, SMS, WhatsApp, booking, loyalty, invoicing, reports, AI",
        "tools": ["Multi-tenant", "Custom domains", "White-label dashboard", "API", "Client portal", "Billing", "Marketplace", "SSO"],
        "target": "Software house, system integrator, telco, banche, assicurazioni, franchisor, buying groups"
    },
    "no_code_automation_builder_local": {
        "name": "Costruttore Automazioni No-Code per Locali",
        "price_range": "€49-299/mese",
        "frequency": "monthly",
        "automation_level": "high",
        "current_mrr": 0,
        "potential_mrr": 5000,
        "description": "Zapier/Make per locali: automazioni visive per prenotazioni, recensioni, marketing, ordini, staff, inventario",
        "tools": ["Visual builder", "100+ integrations", "Templates", "AI suggestions", "Testing", "Deploy", "Monitoring"],
        "target": "Proprietari locali tech-savvy, agenzie, consulenti, system integrator, figli proprietari"
    }
}

# ============================================================
# PRIORITY MATRIX V4
# ============================================================

PRIORITY_V4 = {
    "this_week": [  # Can launch THIS WEEK with existing infra
        "ai_local_ad_manager",
        "ai_social_ad_manager",
        "ai_review_generation",
        "ai_gmb_optimizer",
        "ai_local_seo_citations",
        "birthday_anniversary_marketing",
        "referral_program_automation",
        "gift_card_platform",
    ],
    "week_2_4": {
        "focus": "Revenue Optimization + WhatsApp CRM + Booking",
        "streams": [
            "menu_engineering_ai",
            "ai_upsell_engine",
            "dynamic_pricing_ai",
            "waste_reduction_ai",
            "whatsapp_crm",
            "appointment_booking_saas",
            "loyalty_program_saas",
            "gift_card_platform",
            "ai_local_ad_manager",
            "ai_social_ad_manager",
            "ai_influencer_marketing_local",
        ]
    },
    "month_2": {
        "focus": "Operations + Customer Lifecycle + Marketplace + Ads",
        "streams": [
            "clv_calculator",
            "churn_prediction",
            "referral_program_automation",
            "staff_scheduling_ai",
            "inventory_management_ai",
            "vendor_price_comparison",
            "compliance_automation",
            "catering_lead_gen",
            "private_dining_booking",
            "b2b_lead_marketplace",
            "ai_local_ad_manager",
            "ai_social_ad_manager",
            "ai_influencer_marketing_local",
            "ai_pr_distribution_local",
        ]
    },
    "month_3": {
        "focus": "High-Value Niche + Whitelabel SaaS + Franchise",
        "streams": [
            "ghost_kitchen_optimizer",
            "virtual_brand_launcher",
            "franchise_compliance_monitor",
            "white_label_saas_platform",
            "agency_partner_program",
            "developer_api_marketplace",
            "franchise_compliance_monitor",
            "franchise_lead_gen_automated",
            "multi_location_seo_manager",
        ]
    },
    "month_4_6": {
        "focus": "Scale + Financial + Vertical + ESG + Emerging",
        "streams": [
            "pos_financing_marketplace",
            "insurance_marketplace",
            "tax_compliance_automation",
            "staff_training_lms",
            "digital_transformation_consulting",
            "carbon_footprint_tracking",
            "sustainable_sourcing_tracker",
            "restaurant_revenue_optimizer",
            "hotel_revenue_management",
            "gym_retention_optimizer",
            "beauty_salon_optimizer",
            "local_business_lending_marketplace",
            "pos_financing_automation",
            "merchant_cash_advance_broker",
            "commercial_lease_optimizer",
            "location_intelligence_saas",
            "retail_site_selector",
            "food_waste_tracking_ai",
            "sustainable_menu_optimizer",
            "esg_reporting_automation",
            "hospitality_staffing_marketplace",
            "hospitality_training_automation",
            "local_business_api_marketplace",
            "local_business_data_licensing",
            "white_label_local_seo_tool",
            "ar_menu_experience",
            "voice_ordering_assistant",
            "ai_phone_receptionist",
            "foot_traffic_data_licensing",
            "local_search_trends_api",
            "business_automation_platform_whitelabel",
            "no_code_automation_builder_local",
        ]
    }
}

# ============================================================
# TOTAL TAM CALCULATION
# ============================================================

def calculate_total_tam_v4():
    """Calcola TAM totale combinando tutti gli stream v1-v4."""
    all_streams = {}
    
    # Import existing
    try:
        import new_revenue_streams as nrs
        import additional_revenue_streams_v2 as ars2
        import revenue_streams_v3 as rs3
        all_streams.update(nrs.REVENUE_STREAMS)
        all_streams.update(ars2.ADDITIONAL_STREAMS)
        all_streams.update(rs3.EXTENDED_STREAMS)
    except:
        pass
    all_streams.update(EXTENDED_STREAMS_V4)
    
    total_potential = sum(s.get("potential_mrr", 0) for s in all_streams.values())
    total_current = sum(s.get("current_mrr", 0) for s in all_streams.values())
    high_auto = sum(s.get("potential_mrr", 0) for s in all_streams.values() if s.get("automation_level") == "high")
    med_auto = sum(s.get("potential_mrr", 0) for s in all_streams.values() if s.get("automation_level") == "medium")
    low_auto = sum(s.get("potential_mrr", 0) for s in all_streams.values() if s.get("automation_level") == "low")
    
    return {
        "total_streams": len(all_streams),
        "total_potential_mrr": total_potential,
        "current_mrr": total_current,
        "gap": total_potential - total_current,
        "high_automation_mrr": high_auto,
        "medium_automation_mrr": med_auto,
        "low_automation_mrr": low_auto,
        "high_automation_pct": round(high_auto / total_potential * 100, 1)
    }

def print_full_summary_v4():
    tam = calculate_total_tam_v4()
    all_streams = EXTENDED_STREAMS_V4.copy()
    try:
        import new_revenue_streams as nrs
        import additional_revenue_streams_v2 as ars2
        import revenue_streams_v3 as rs3
        all_streams.update(nrs.REVENUE_STREAMS)
        all_streams.update(ars2.ADDITIONAL_STREAMS)
        all_streams.update(rs3.EXTENDED_STREAMS)
    except:
        pass
    
    print(f"\n{'='*80}")
    print(f" GHOST AGENCY - REVENUE STREAMS MASTER SUMMARY (v4 FINAL)")
    print(f"{'='*80}")
    print(f"Total Streams: {tam['total_streams']}")
    print(f"Potential MRR: €{tam['total_potential_mrr']:,.0f}/mese")
    print(f"Current MRR: €{tam['current_mrr']:,.0f}/mese")
    print(f"Gap: €{tam['gap']:,.0f}/mese")
    print(f"High Automation: €{tam['high_automation_mrr']:,.0f} ({tam['high_automation_pct']}%)")
    print(f"Medium Automation: €{tam['medium_automation_mrr']:,.0f}")
    print(f"Low Automation: €{tam['low_automation_mrr']:,.0f}")
    
    # Top 25
    all_streams = EXTENDED_STREAMS_V4.copy()
    try:
        import new_revenue_streams as nrs
        import additional_revenue_streams_v2 as ars2
        import revenue_streams_v3 as rs3
        all_streams.update(nrs.REVENUE_STREAMS)
        all_streams.update(ars2.ADDITIONAL_STREAMS)
        all_streams.update(rs3.EXTENDED_STREAMS)
    except:
        pass
    
    print(f"\n{'#':<3} {'Stream':<55} {'Potential MRR':>12} {'Auto':>6} {'Status'}")
    print("-"*80)
    for i, (key, stream) in enumerate(sorted(all_streams.items(), key=lambda x: x[1].get("potential_mrr", 0), reverse=True)[:25], 1):
        auto = stream.get("automation_level", "N/A")[:6]
        status = "���� Live" if stream.get("current_mrr", 0) > 0 else "���� Planned"
        print(f"{i:<3} {stream.get('name', key)[:53]:<55} €{stream.get('potential_mrr', 0):>10,} {auto:>6} {status}")

    print(f"\n\nQUICK WINS (This Week - High Auto + High Value):")
    for stream in PRIORITY_V4["this_week"]:
        s = all_streams.get(stream, {})
        print(f"  • {s.get('name', stream)} - €{s.get('potential_mrr', 0):,}/mese ({s.get('automation_level', 'N/A')})")

if __name__ == "__main__":
    print_full_summary_v4()