#!/usr/bin/env python3
"""
Ghost Agency - Revenue Dashboard API
Complete revenue tracking dashboard with all metrics
"""

import os
import json
import sqlite3
from pathlib import Path
from datetime import datetime, timedelta
from flask import Flask, jsonify, request, send_from_directory

LEADS_DIR = Path("/home/ubuntu/GhostAgency")
DB_FILE = Path("/home/ubuntu/GhostAgency") / "revenue_bots.db"
BROKER_DB = Path("/home/ubuntu/GhostAgency") / "lead_broker.db"
CONTENT_DB = Path("/home/ubuntu/GhostAgency") / "content_calendar.db"
SEO_DB = Path("/home/ubuntu/GhostAgency") / "seo_optimizer.db"
WHATSAPP_DB = Path("/home/ubuntu/GhostAgency") / "whatsapp_crm.db"

app = Flask(__name__)

# ============================================================
# HELPER FUNCTIONS
# ============================================================

def get_db_connection(db_path):
    conn = sqlite3.connect(db_path)
    conn.row_factory = sqlite3.Row
    return conn

def format_currency(val):
    if val is None:
        return "€0"
    return "€{:,.0f}".format(val)

def format_number(val):
    if val is None:
        return "0"
    return "{:,}".format(val)

# ============================================================
# API ROUTES
# ============================================================

@app.route("/")
def dashboard():
    return send_from_directory("/home/ubuntu/GhostAgency", "dashboard.html")

@app.route("/api/revenue/summary")
def revenue_summary():
    """Get complete revenue summary across all systems."""
    try:
        # Revenue Bots DB
        conn = sqlite3.connect("/home/ubuntu/GhostAgency/revenue_bots.db")
        c = conn.cursor()
        
        # MRR from clients
        c.execute("SELECT SUM(monthly_fee) FROM clients WHERE stato='attivo'")
        mrr = c.fetchone()[0] or 0
        
        # Setup fees this month
        c.execute("""SELECT SUM(importo) FROM revenue_events 
                     WHERE tipo='setup' AND data > date('now', 'start of month')""")
        setup_month = c.fetchone()[0] or 0
        
        # Upsells this month
        c.execute("""SELECT SUM(importo_mensile) FROM upsells 
                     WHERE stato='accettato' AND accettato_at > date('now', 'start of month')""")
        upsell_mrr = c.fetchone()[0] or 0
        
        # Renewals this month
        c.execute("""SELECT SUM(importo) FROM renewals 
                     WHERE stato='paid' AND pagato_at > date('now', 'start of month')""")
        renewals_month = c.fetchone()[0] or 0
        
        # Referrals
        c.execute("SELECT COUNT(*) FROM referrals WHERE pagato=1")
        referrals_paid = c.fetchone()[0] or 0
        referral_cost = referrals_paid * 100
        
        # Upsell pipeline
        c.execute("SELECT COUNT(*), SUM(importo_mensile) FROM upsells WHERE stato='proposto'")
        upsell_pipeline = c.fetchone()
        upsell_count = upsell_pipeline[0] or 0
        upsell_value = upsell_pipeline[1] or 0
        
        # Upcoming renewals
        c.execute("""SELECT COUNT(*) FROM renewals 
                     WHERE stato='pending' AND date(scadenza) BETWEEN date('now') AND date('now', '+30 days')""")
        upcoming_renewals = c.fetchone()[0] or 0
        
        # Overdue renewals
        c.execute("SELECT COUNT(*) FROM renewals WHERE stato='overdue'")
        overdue_renewals = c.fetchone()[0] or 0
        
        conn.close()
        
        # Lead Broker DB
        broker_conn = sqlite3.connect("/home/ubuntu/GhostAgency/lead_broker.db")
        c = broker_conn.cursor()
        
        total_leads = c.execute("SELECT COUNT(*) FROM leads_inventory").fetchone()[0] or 0
        available_leads = c.execute("SELECT COUNT(*) FROM leads_inventory WHERE venduto=0").fetchone()[0] or 0
        sold_leads = c.execute("SELECT COUNT(*) FROM leads_inventory WHERE venduto=1").fetchone()[0] or 0
        total_revenue = c.execute("SELECT SUM(prezzo) FROM sales").fetchone()[0] or 0
        total_commission = c.execute("SELECT SUM(commission_fee) FROM sales").fetchone()[0] or 0
        
        broker_conn.close()
        
        # Content DB
        content_conn = sqlite3.connect("/home/ubuntu/GhostAgency/content_calendar.db")
        c = content_conn.cursor()
        content_posts = c.execute("SELECT COUNT(*) FROM content_posts").fetchone()[0] or 0
        content_calendars = c.execute("SELECT COUNT(*) FROM content_calendar").fetchone()[0] or 0
        content_conn.close()
        
        # SEO DB
        seo_conn = sqlite3.connect("/home/ubuntu/GhostAgency/seo_optimizer.db")
        c = seo_conn.cursor()
        seo_sites = c.execute("SELECT COUNT(*) FROM tracked_sites WHERE status='active'").fetchone()[0] or 0
        seo_tasks = c.execute("SELECT COUNT(*) FROM optimization_tasks WHERE status='pending'").fetchone()[0] or 0
        seo_audits = c.execute("SELECT COUNT(*) FROM seo_audits").fetchone()[0] or 0
        seo_conn.close()
        
        # WhatsApp DB
        wa_conn = sqlite3.connect("/home/ubuntu/GhostAgency/whatsapp_crm.db")
        c = wa_conn.cursor()
        wa_clients = c.execute("SELECT COUNT(*) FROM whatsapp_clients WHERE active=1").fetchone()[0] or 0
        wa_contacts = c.execute("SELECT COUNT(*) FROM contacts").fetchone()[0] or 0
        wa_flows = c.execute("SELECT COUNT(*) FROM bot_flows WHERE active=1").fetchone()[0] or 0
        wa_conn.close()
        
        # Revenue Bots DB for detailed stats
        rb_conn = sqlite3.connect("/home/ubuntu/GhostAgency/revenue_bots.db")
        c = rb_conn.cursor()
        
        # Upsell pipeline details
        c.execute("SELECT tipo, COUNT(*), SUM(importo_mensile) FROM upsells WHERE stato='proposto' GROUP BY tipo")
        upsell_by_type = c.fetchall()
        
        # Upcoming renewals details
        c.execute("""SELECT r.tipo, r.scadenza, r.importo, c.nome 
                     FROM renewals r JOIN clients c ON r.client_id=c.id 
                     WHERE r.stato='pending' AND date(r.scadenza) BETWEEN date('now') AND date('now', '+30 days')
                     ORDER BY r.scadenza""")
        upcoming_renewals_detail = c.fetchall()
        
        # Client details
        c.execute("SELECT nome, piano, monthly_fee, stato FROM clients WHERE stato='attivo'")
        active_clients = c.fetchall()
        
        conn.close()
        
        # Build response
        kpis = {
            "mrr": mrr,
            "setup_month": setup_month,
            "upsell_mrr": upsell_mrr,
            "renewals_month": renewals_month,
            "referrals_paid": referrals_paid,
            "referral_cost": referral_cost,
            "net_month": setup_month + renewals_month - referral_cost,
            "projected_mrr": mrr + upsell_mrr
        }
        
        pipeline = {
            "upsell_count": upsell_count,
            "upsell_value": upsell_value,
            "upsell_by_type": [{"type": u[0], "count": u[1], "value": u[2]} for u in upsell_by_type],
            "upcoming_renewals": upcoming_renewals,
            "overdue_renewals": overdue_renewals,
            "upcoming_renewals_detail": []
        }
        
        for u in upcoming_renewals_detail:
            pipeline["upcoming_renewals_detail"].append({
                "tipo": u[0],
                "scadenza": u[1],
                "importo": u[2],
                "cliente": u[3]
            })
        
        lead_broker = {
            "total_leads": total_leads,
            "available": available_leads,
            "sold": sold_leads,
            "revenue": total_revenue,
            "commission": total_commission,
            "net": total_revenue - total_commission
        }
        
        content = {
            "posts_generated": content_posts,
            "calendars_created": content_calendars
        }
        
        seo = {
            "sites_tracked": seo_sites,
            "pending_tasks": seo_tasks,
            "audits_completed": seo_audits
        }
        
        whatsapp = {
            "active_clients": wa_clients,
            "contacts": wa_contacts,
            "active_flows": wa_flows
        }
        
        clients = []
        for c in active_clients:
            clients.append({
                "nome": c[0],
                "piano": c[1],
                "mrr": c[2],
                "stato": c[3]
            })
        
        return jsonify({
            "timestamp": datetime.now().isoformat(),
            "kpis": kpis,
            "pipeline": pipeline,
            "lead_broker": lead_broker,
            "content": content,
            "seo": seo,
            "whatsapp": whatsapp,
            "clients": clients
        })
    except Exception as e:
        return jsonify({"error": str(e)}), 500

@app.route("/api/leads/available")
def leads_available():
    """Get available leads for purchase."""
    broker_conn = sqlite3.connect("/home/ubuntu/GhostAgency/lead_broker.db")
    c = broker_conn.cursor()
    
    categoria = request.args.get('categoria')
    citta = request.args.get('citta', 'Parma')
    has_email = request.args.get('has_email')
    min_price = request.args.get('min_price', type=float)
    max_price = request.args.get('max_price', type=float)
    limit = min(int(request.args.get('limit', 50)), 200)
    offset = int(request.args.get('offset', 0))
    
    conn = sqlite3.connect("/home/ubuntu/GhostAgency/lead_broker.db")
    c = conn.cursor()
    
    query = """
        SELECT id, nome, email, telefono, indirizzo, categoria, citta, 
               fonte, data_scoperta, prezzo
        FROM leads_inventory 
        WHERE venduto = 0 AND citta = ?
    """
    params = [citta]
    
    if categoria:
        query += " AND categoria = ?"
        params.append(categoria)
    
    if has_email == 'true':
        query += " AND email IS NOT NULL AND email != ''"
    elif has_email == 'false':
        query += " AND (email IS NULL OR email = '')"
    
    if min_price is not None:
        query += " AND prezzo >= ?"
        params.append(min_price)
    
    if max_price is not None:
        query += " AND prezzo <= ?"
        params.append(max_price)
    
    query += " ORDER BY prezzo DESC, data_scoperta DESC LIMIT ? OFFSET ?"
    params.extend([limit, offset])
    
    leads = c.execute(query, params).fetchall()
    
    count_query = query.replace("SELECT id, nome, email, telefono, indirizzo, categoria, citta, fonte, data_scoperta, prezzo", "SELECT COUNT(*)")
    count_query = count_query.replace("ORDER BY prezzo DESC, data_scoperta DESC LIMIT ? OFFSET ?", "")
    total = c.execute(count_query, params[:-2]).fetchone()[0]
    
    conn.close()
    
    leads_list = []
    for row in leads:
        leads_list.append(dict(zip(["id", "nome", "email", "telefono", "indirizzo", "categoria", "citta", "fonte", "data_scoperta", "prezzo"], row)))
    
    return jsonify({
        "leads": leads_list,
        "pagination": {"total": total, "limit": limit, "offset": offset, "has_more": (offset + limit) < total}
    })

@app.route("/api/leads/purchase", methods=["POST"])
def purchase_leads():
    """Purchase leads."""
    data = request.get_json()
    lead_ids = data.get("lead_ids", [])
    
    if not lead_ids or not isinstance(lead_ids, list):
        return jsonify({"error": "lead_ids required"}), 400
    
    conn = sqlite3.connect("/home/ubuntu/GhostAgency/lead_broker.db")
    c = conn.cursor()
    
    # Check availability
    placeholders = ','.join('?' * len(lead_ids))
    leads = c.execute("""
        SELECT id, prezzo FROM leads_inventory 
        WHERE id IN ({}) AND venduto = 0
    """.format(placeholders), lead_ids).fetchall()
    
    if len(leads) != len(lead_ids):
        return jsonify({"error": "Some leads not available"}), 409
    
    total = 0
    sales = []
    for lead in leads:
        lead_id, prezzo = lead
        commission = prezzo * 0.1
        netto = prezzo - commission
        
        c.execute("UPDATE leads_inventory SET venduto=1, venduto_at=?, buyer_id=? WHERE id=?", 
                  (datetime.now().isoformat(), "direct", lead_id))
        
        c.execute("""INSERT INTO sales (lead_id, buyer_id, prezzo, commission_fee, netto, delivery_status)
                     VALUES (?, ?, ?, ?, ?, 'delivered')""",
                  (lead_id, "direct", prezzo, commission, netto))
        
        sales.append({"lead_id": lead_id, "prezzo": prezzo, "commission": commission, "netto": netto})
        total += prezzo
    
    conn.commit()
    conn.close()
    
    return jsonify({"success": True, "purchased": len(sales), "total": total, "sales": sales})

@app.route("/api/seo/sites")
def seo_sites():
    """Get tracked SEO sites."""
    conn = sqlite3.connect("/home/ubuntu/GhostAgency/seo_optimizer.db")
    c = conn.cursor()
    c.execute("SELECT id, url, business_name, category, status FROM tracked_sites WHERE status='active'")
    sites = c.fetchall()
    conn.close()
    return jsonify({"sites": [dict(zip(["id", "url", "business_name", "category", "status"], s)) for s in sites]})

@app.route("/api/seo/audit/<site_id>", methods=["POST"])
def run_seo_audit(site_id):
    """Run SEO audit for a site."""
    import subprocess
    import os
    
    env = os.environ.copy()
    env.update({
        "HUNTER_API_KEY": "922878...e999",
        "GOOGLE_MAPS_API_KEY": "922878...e999",
        "OPENROUTER_API_KEY": "nvapi-...PYvY",
    })
    
    result = subprocess.run(
        ["/home/ubuntu/venv/bin/python3", "-c", """
import sys
sys.path.insert(0, '/home/ubuntu/GhostAgency')
from ai_seo_optimizer import AISEOOptimizer
optimizer = AISEOOptimizer()
result = optimizer.run_full_audit('{0}')
print(json.dumps(result))
""".format(site_id)],
        capture_output=True, text=True, timeout=60,
        env={**os.environ, "HUNTER_API_KEY": "922878...e999", "GOOGLE_MAPS_API_KEY": "922878...e999", "OPENROUTER_API_KEY": "nvapi-...PYvY"})
    
    try:
        result_data = json.loads(result.stdout.strip().split('\n')[-1])
        return jsonify(result_data)
    except:
        return jsonify({"error": "Audit failed", "output": result.stdout[:500]})

@app.route("/api/revenue/clients")
def revenue_clients():
    """Get all clients with revenue details."""
    conn = sqlite3.connect("/home/ubuntu/GhostAgency/revenue_bots.db")
    c = conn.cursor()
    c.execute("""SELECT nome, piano, monthly_fee, setup_fee, stato, 
                        (SELECT COUNT(*) FROM upsells WHERE client_id=c.id AND stato='proposto') as upsell_count,
                        (SELECT COUNT(*) FROM renewals WHERE client_id=c.id AND stato='pending') as pending_renewals
                 FROM clients c WHERE c.stato='attivo'""")
    clients = c.fetchall()
    conn.close()
    return jsonify({"clients": [dict(zip(["nome", "piano", "mrr", "setup_fee", "stato", "upsell_count", "pending_renewals"], c)) for c in clients]})

@app.route("/api/leads/stats")
def leads_stats():
    """Get lead statistics."""
    conn = sqlite3.connect("/home/ubuntu/GhostAgency/lead_broker.db")
    c = conn.cursor()
    
    citta = request.args.get('citta', 'Parma')
    
    by_category = c.execute("""
        SELECT categoria, COUNT(*) as count, AVG(prezzo) as avg_price, SUM(prezzo) as total_value
        FROM leads_inventory WHERE venduto = 0 AND citta = ?
        GROUP BY categoria ORDER BY count DESC
    """, (citta,)).fetchall()
    
    by_source = c.execute("""
        SELECT fonte, COUNT(*) as count
        FROM leads_inventory WHERE venduto = 0 AND citta = ?
        GROUP BY fonte
    """, (citta,)).fetchall()
    
    email_stats = c.execute("""
        SELECT SUM(CASE WHEN email IS NOT NULL AND email != '' THEN 1 ELSE 0 END) as with_email,
               SUM(CASE WHEN email IS NULL OR email = '' THEN 1 ELSE 0 END) as without_email
        FROM leads_inventory WHERE venduto = 0 AND citta = ?
    """, (citta,)).fetchone()
    
    sold_month = c.execute("""
        SELECT COUNT(*) as count, SUM(prezzo) as revenue
        FROM sales WHERE strftime('%Y-%m', venduto_at) = ?
    """, (datetime.now().strftime('%Y-%m'),)).fetchone()
    
    conn.close()
    
    return jsonify({
        "by_category": [dict(row) for row in by_category],
        "by_source": [dict(row) for row in by_source],
        "email_stats": dict(email_stats) if email_stats else {},
        "monthly_purchases": dict(sold_month) if sold_month else {"count": 0, "revenue": 0}
    })

@app.route("/api/content/stats")
def content_stats():
    """Content generation statistics."""
    conn = sqlite3.connect("/home/ubuntu/GhostAgency/content_calendar.db")
    c = conn.cursor()
    
    total_posts = c.execute("SELECT COUNT(*) FROM content_posts").fetchone()[0] or 0
    total_calendars = c.execute("SELECT COUNT(*) FROM content_calendar").fetchone()[0] or 0
    
    by_status = c.execute("SELECT status, COUNT(*) as count FROM content_posts GROUP BY status").fetchall()
    by_platform = c.execute("SELECT platform, COUNT(*) as count FROM content_posts GROUP BY platform").fetchall()
    by_type = c.execute("SELECT content_type, COUNT(*) as count FROM content_posts GROUP BY content_type").fetchall()
    
    conn.close()
    
    return jsonify({
        "total_posts": total_posts,
        "total_calendars": total_calendars,
        "by_status": [dict(row) for row in by_status],
        "by_platform": [dict(row) for row in by_platform],
        "by_type": [dict(row) for row in by_type]
    })

@app.route("/api/seo/tasks")
def seo_tasks():
    """Get pending SEO tasks."""
    conn = sqlite3.connect("/home/ubuntu/GhostAgency/seo_optimizer.db")
    c = conn.cursor()
    c.execute("""SELECT ot.*, ts.url, ts.business_name 
                 FROM optimization_tasks ot
                 JOIN tracked_sites ts ON ot.site_id = ts.id
                 WHERE ot.status='pending'
                 ORDER BY ot.priority DESC, ot.created_at""")
    tasks = c.fetchall()
    conn.close()
    return jsonify({"tasks": [dict(zip(["id", "site_id", "task_type", "priority", "title", "description", "target_url", "current_state", "recommended_action", "estimated_impact", "status", "created_at", "url", "business_name"], t)) for t in tasks]})

@app.route("/api/revenue/upsells")
def revenue_upsells():
    """Get upsell pipeline."""
    conn = sqlite3.connect("/home/ubuntu/GhostAgency/revenue_bots.db")
    c = conn.cursor()
    c.execute("""SELECT u.*, c.nome as client_name 
                 FROM upsells u JOIN clients c ON u.client_id = c.id
                 WHERE u.stato='proposto'
                 ORDER BY u.proposto_at DESC""")
    upsells = c.fetchall()
    conn.close()
    return jsonify({"upsells": [dict(zip(["id", "client_id", "tipo", "importo_mensile", "importo_setup", "stato", "proposto_at", "note", "client_name"], u)) for u in upsells]})

@app.route("/api/revenue/renewals")
def revenue_renewals():
    """Get renewal calendar."""
    conn = sqlite3.connect("/home/ubuntu/GhostAgency/revenue_bots.db")
    c = conn.cursor()
    c.execute("""SELECT r.*, c.nome as client_name 
                 FROM renewals r JOIN clients c ON r.client_id = c.id
                 WHERE r.stato IN ('pending', 'overdue')
                 ORDER BY r.scadenza ASC""")
    renewals = c.fetchall()
    conn.close()
    return jsonify({"renewals": [dict(zip(["id", "client_id", "tipo", "scadenza", "importo", "stato", "reminder_1", "reminder_2", "reminder_3", "client_name"], r)) for r in renewals]})

@app.route("/api/content/calendar")
def content_calendar():
    """Get content calendar."""
    conn = sqlite3.connect("/home/ubuntu/GhostAgency/content_calendar.db")
    c = conn.cursor()
    c.execute("""SELECT cc.*, cp.caption, cp.platform, cp.content_type, cp.scheduled_at, cp.status as post_status
                 FROM content_calendar cc
                 LEFT JOIN content_posts cp ON cc.client_id = cp.client_id
                 ORDER BY cc.week_start DESC""")
    calendars = c.fetchall()
    conn.close()
    return jsonify({"calendars": [dict(row) for row in calendars]})

@app.route("/api/whatsapp/clients")
def whatsapp_clients():
    """Get WhatsApp CRM clients."""
    conn = sqlite3.connect("/home/ubuntu/GhostAgency/whatsapp_crm.db")
    c = conn.cursor()
    c.execute("SELECT id, business_name, business_category, active FROM whatsapp_clients WHERE active=1")
    clients = c.fetchall()
    conn.close()
    return jsonify({"clients": [dict(zip(["id", "business_name", "category", "active"], c)) for c in clients]})

@app.route("/api/revenue/report")
def revenue_report():
    """Complete revenue report."""
    conn = sqlite3.connect("/home/ubuntu/GhostAgency/revenue_bots.db")
    c = conn.cursor()
    
    mrr = c.execute("SELECT SUM(monthly_fee) FROM clients WHERE stato='attivo'").fetchone()[0] or 0
    setup_month = c.execute("SELECT SUM(importo) FROM revenue_events WHERE tipo='setup' AND data > date('now', 'start of month')").fetchone()[0] or 0
    upsell_mrr = c.execute("SELECT SUM(importo_mensile) FROM upsells WHERE stato='accettato' AND accettato_at > date('now', 'start of month')").fetchone()[0] or 0
    renewals_month = c.execute("SELECT SUM(importo) FROM renewals WHERE stato='paid' AND pagato_at > date('now', 'start of month')").fetchone()[0] or 0
    referrals_paid = c.execute("SELECT COUNT(*) FROM referrals WHERE pagato=1").fetchone()[0] or 0
    referral_cost = referrals_paid * 100
    
    # Pipeline
    c.execute("SELECT COUNT(*), SUM(importo_mensile) FROM upsells WHERE stato='proposto'")
    pipeline = c.fetchone()
    
    c.execute("SELECT COUNT(*) FROM renewals WHERE stato='pending' AND date(scadenza) BETWEEN date('now') AND date('now', '+30 days')")
    upcoming = c.fetchone()[0] or 0
    
    c.execute("SELECT COUNT(*) FROM renewals WHERE stato='overdue'")
    overdue = c.fetchone()[0] or 0
    
    conn.close()
    
    return jsonify({
        "mrr": mrr,
        "setup_month": setup_month,
        "upsell_mrr": upsell_mrr,
        "renewals_month": renewals_month,
        "referrals_paid": referrals_paid,
        "referral_cost": referrals_paid * 100,
        "net_month": setup_month + renewals_month - referral_cost,
        "projected_mrr": mrr + upsell_mrr,
        "pipeline": {"count": pipeline[0] or 0, "value": pipeline[1] or 0},
        "upcoming_renewals": upcoming,
        "overdue_renewals": overdue
    })

@app.route("/api/status")
def system_status():
    """Overall system health check."""
    checks = {}
    
    # Check databases
    for name, path in [("revenue_bots", "/home/ubuntu/GhostAgency/revenue_bots.db"),
                       ("lead_broker", "/home/ubuntu/GhostAgency/lead_broker.db"),
                       ("content_calendar", "/home/ubuntu/GhostAgency/content_calendar.db"),
                       ("seo_optimizer", "/home/ubuntu/GhostAgency/seo_optimizer.db"),
                       ("whatsapp_crm", "/home/ubuntu/GhostAgency/whatsapp_crm.db")]:
        try:
            conn = sqlite3.connect(path)
            conn.execute("SELECT 1")
            conn.close()
            checks[name] = "healthy"
        except:
            checks[name] = "unhealthy"
    
    # Check API services
    try:
        import requests
        resp = requests.get("http://localhost:8080/health", timeout=2)
        checks["lead_broker_api"] = "healthy" if resp.status_code == 200 else "unhealthy"
    except:
        checks["lead_broker_api"] = "unhealthy"
    
    try:
        resp = requests.get("http://localhost:8081/health", timeout=2)
        checks["admin_api"] = "healthy" if resp.status_code == 200 else "unhealthy"
    except:
        checks["admin_api"] = "unhealthy"
    
    return jsonify({"status": "operational" if all(v == "healthy" for v in checks.values()) else "degraded", "checks": checks, "timestamp": datetime.now().isoformat()})

# ============================================================
# MAIN
# ============================================================

if __name__ == "__main__":
    print("Starting Ghost Agency Revenue Dashboard API on port 8082...")
    app.run(host="0.0.0.0", port=8082, debug=False)