#!/usr/bin/env python3
"""
Ghost Agency - WhatsApp CRM MVP
Automated WhatsApp Business API integration for local businesses
"""

import os
import json
import sqlite3
import hashlib
import time
import random
import requests
from pathlib import Path
from datetime import datetime, timedelta
from typing import Dict, List, Any, Optional
from dataclasses import dataclass, asdict
from flask import Flask, request, jsonify

LEADS_DIR = Path("/home/ubuntu/GhostAgency")
DB_FILE = Path("/home/ubuntu/GhostAgency") / "revenue_bots.db"
WHATSAPP_DB = Path("/home/ubuntu/GhostAgency") / "whatsapp_crm.db"

# ============================================================
# WHATSAPP BUSINESS API CONFIGURATION
# ============================================================

WHATSAPP_CONFIG = {
    "meta_cloud_api": {
        "base_url": "https://graph.facebook.com/v18.0",
        "phone_number_id": os.getenv("META_PHONE_NUMBER_ID", ""),
        "access_token": os.getenv("META_WHATSAPP_TOKEN", ""),
        "verify_token": os.getenv("META_VERIFY_TOKEN", "ghost_agency_webhook_verify"),
        "webhook_url": "https://svoraj.me/webhook/whatsapp"
    },
    "templates": {
        "booking_confirmation": {
            "name": "booking_confirmation",
            "language": "it",
            "components": [
                {"type": "header", "format": "TEXT", "text": "��� Prenotazione Confermata"},
                {"type": "body", "text": "Ciao {{1}}! La tua prenotazione da {{2}} è confermata per il {{3}} alle {{4}}.\n\nDettagli:\n���� Indirizzo: {{5}}\n���� Telefono: {{6}}\n\nTi aspettiamo!"},
                {"type": "footer", "text": "Grazie per aver scelto {{2}}! | {{3}}"}
            ]
        },
        "booking_reminder": {
            "name": "booking_reminder",
            "language": "it",
            "components": [
                {"type": "header", "format": "TEXT", "text": "��� Promemoria Prenotazione"},
                {"type": "body", "text": "Ciao {{1}}! Ti ricordiamo la tua prenotazione da {{2}} domani alle {{3}}.\n\n���� {{4}}\n���� {{5}}\n\nSe devi modificare o annullare, rispondi a questo messaggio."},
                {"type": "footer", "text": "A domani! | {{2}}"}
            ]
        },
        "review_request": {
            "name": "review_request",
            "language": "it",
            "components": [
                {"type": "header", "format": "TEXT", "text": "��� La tua opinione conta!"},
                {"type": "body", "text": "Ciao {{1}}! Grazie per aver scelto {{2}}.\n\nCome è andata? La tua opinione ci aiuta a migliorare.\n\nLascia una recensione su Google: {{3}}\n\nGrazie! ���"},
                {"type": "footer", "text": "Grazie! | {{2}}"}
            ]
        },
        "birthday_offer": {
            "name": "birthday_offer",
            "language": "it",
            "components": [
                {"type": "header", "format": "TEXT", "text": "���� Buon Compleanno {{1}}!"},
                {"type": "body", "text": "Tanti auguri da tutto lo staff di {{2}}! ���\n\nCome regalo, ti offriamo: {{3}}\n\nValido fino al {{4}}. Prenota ora: {{5}}\n\nTanti auguri ancora! ���"},
                {"type": "footer", "text": "Offerta valida fino al {{4}} | {{2}}"}
            ]
        },
        "loyalty_reward": {
            "name": "loyalty_reward",
            "language": "it",
            "components": [
                {"type": "header", "format": "TEXT", "text": "���� Hai sbloccato un premio!"},
                {"type": "body", "text": "Complimenti {{1}}! Hai raggiunto {{2}} punti fedeltà.\n\nIl tuo premio: {{3}}\n\nRiscattalo entro il {{4}} da {{5}}.\n\nGrazie per la tua fedeltà! ������"},
                {"type": "footer", "text": "Valido fino al {{4}} | {{5}}"}
            ]
        },
        "promotional_broadcast": {
            "name": "promotional_broadcast",
            "language": "it",
            "components": [
                {"type": "header", "format": "TEXT", "text": "���� Novità da {{1}}!"},
                {"type": "body", "text": "Ciao {{2}}! Abbiamo una novità per te: {{3}}\n\n{{4}}\n\nPrenota ora: {{5}}\n\nTi aspettiamo! ���"},
                {"type": "footer", "text": "Valido fino al {{6}} | {{1}}"}
            ]
        },
        "faq_autoresponder": {
            "name": "faq_autoresponder",
            "language": "it",
            "components": [
                {"type": "header", "format": "TEXT", "text": "���� Assistente Virtuale {{1}}"},
                {"type": "body", "text": "Ciao! Sono l'assistente virtuale di {{1}}.\n\nCome posso aiutarti?\n\n1������ Prenota un appuntamento\n2������ Orari e indirizzo\n3������ Menu/Servizi\n4������ Parla con un umano\n\nRispondi con il numero dell'opzione!"},
                {"type": "footer", "text": "{{1}} - Sempre qui per te"}
            ]
        }
    }
}

# ============================================================
# WHATSAPP CRM DATABASE
# ============================================================

WHATSAPP_DB = Path("/home/ubuntu/GhostAgency") / "whatsapp_crm.db"

class WhatsAppCRM:
    def __init__(self):
        self.db_path = str(WHATSAPP_DB)
        self.config = WHATSAPP_CONFIG
        self.init_db()
    
    def init_db(self):
        conn = sqlite3.connect(self.db_path)
        c = conn.cursor()
        
        # Clients/Businesses using the CRM
        c.execute("""CREATE TABLE IF NOT EXISTS whatsapp_clients (
            id TEXT PRIMARY KEY,
            business_name TEXT NOT NULL,
            business_category TEXT,
            phone_number_id TEXT,
            access_token TEXT,
            verify_token TEXT,
            webhook_url TEXT,
            business_phone TEXT,
            address TEXT,
            templates_approved INTEGER DEFAULT 0,
            active INTEGER DEFAULT 1,
            created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP
        )""")
        
        # Contacts/Clients of the business
        c.execute("""CREATE TABLE IF NOT EXISTS contacts (
            id TEXT PRIMARY KEY,
            client_id TEXT NOT NULL,
            name TEXT,
            phone TEXT NOT NULL,
            email TEXT,
            tags TEXT,  -- JSON array
            custom_fields TEXT,  -- JSON
            opted_in INTEGER DEFAULT 1,
            opted_in_at TIMESTAMP,
            opted_out_at TIMESTAMP,
            created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
            updated_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
            FOREIGN KEY (client_id) REFERENCES whatsapp_clients(id)
        )""")
        
        # Conversations
        c.execute("""CREATE TABLE IF NOT EXISTS conversations (
            id TEXT PRIMARY KEY,
            client_id TEXT NOT NULL,
            contact_id TEXT NOT NULL,
            status TEXT DEFAULT 'open',  -- open, closed, pending, bot
            assigned_to TEXT,  -- bot, human, queue
            last_message_at TIMESTAMP,
            created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
            FOREIGN KEY (client_id) REFERENCES whatsapp_clients(id),
            FOREIGN KEY (contact_id) REFERENCES contacts(id)
        )""")
        
        # Messages
        c.execute("""CREATE TABLE IF NOT EXISTS messages (
            id TEXT PRIMARY KEY,
            conversation_id TEXT NOT NULL,
            client_id TEXT NOT NULL,
            contact_id TEXT NOT NULL,
            direction TEXT NOT NULL,  -- inbound, outbound
            message_type TEXT,  -- text, image, document, template, interactive
            content TEXT,
            template_name TEXT,
            template_params TEXT,  -- JSON
            media_url TEXT,
            media_type TEXT,
            wa_message_id TEXT,
            status TEXT DEFAULT 'sent',  -- sent, delivered, read, failed
            sent_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
            delivered_at TIMESTAMP,
            read_at TIMESTAMP,
            failed_reason TEXT,
            FOREIGN KEY (conversation_id) REFERENCES conversations(id),
            FOREIGN KEY (client_id) REFERENCES whatsapp_clients(id),
            FOREIGN KEY (contact_id) REFERENCES contacts(id)
        )""")
        
        # Templates
        c.execute("""CREATE TABLE IF NOT EXISTS wa_templates (
            id TEXT PRIMARY KEY,
            client_id TEXT NOT NULL,
            template_name TEXT NOT NULL,
            template_id TEXT,  -- Meta template ID
            category TEXT,  -- marketing, utility, authentication
            language TEXT DEFAULT 'it',
            status TEXT DEFAULT 'pending',  -- pending, approved, rejected
            components TEXT,  -- JSON
            created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
            approved_at TIMESTAMP,
            rejected_reason TEXT,
            FOREIGN KEY (client_id) REFERENCES whatsapp_clients(id)
        )""")
        
        # Flows/Bot logic
        c.execute("""CREATE TABLE IF NOT EXISTS bot_flows (
            id TEXT PRIMARY KEY,
            client_id TEXT NOT NULL,
            name TEXT NOT NULL,
            trigger TEXT,  -- keyword, postback, event
            flow_data TEXT,  -- JSON flow definition
            active INTEGER DEFAULT 1,
            created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
            FOREIGN KEY (client_id) REFERENCES whatsapp_clients(id)
        )""")
        
        # Broadcast campaigns
        c.execute("""CREATE TABLE IF NOT EXISTS broadcasts (
            id TEXT PRIMARY KEY,
            client_id TEXT NOT NULL,
            name TEXT,
            template_name TEXT,
            template_params TEXT,  -- JSON
            audience_filter TEXT,  -- JSON
            status TEXT DEFAULT 'draft',  -- draft, scheduled, sending, sent, failed
            scheduled_at TIMESTAMP,
            sent_at TIMESTAMP,
            total_recipients INTEGER DEFAULT 0,
            sent_count INTEGER DEFAULT 0,
            delivered_count INTEGER DEFAULT 0,
            read_count INTEGER DEFAULT 0,
            failed_count INTEGER DEFAULT 0,
            created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
            FOREIGN KEY (client_id) REFERENCES whatsapp_clients(id)
        )""")
        
        # Webhook events log
        c.execute("""CREATE TABLE IF NOT EXISTS webhook_events (
            id TEXT PRIMARY KEY,
            client_id TEXT,
            event_type TEXT,  -- messages, statuses, template_status
            payload TEXT,  -- JSON
            processed INTEGER DEFAULT 0,
            processed_at TIMESTAMP,
            created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP
        )""")
        
        # Automations/Workflows
        c.execute("""CREATE TABLE IF NOT EXISTS automations (
            id TEXT PRIMARY KEY,
            client_id TEXT NOT NULL,
            name TEXT,
            trigger_type TEXT,  -- keyword, event, schedule, webhook
            trigger_config TEXT,  -- JSON
            actions TEXT,  -- JSON array of actions
            active INTEGER DEFAULT 1,
            created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
            FOREIGN KEY (client_id) REFERENCES whatsapp_clients(id)
        )""")
        
        conn.commit()
        conn.close()
    
    def register_client(self, business_data: Dict) -> str:
        """Register a new business/client for WhatsApp CRM."""
        client_id = hashlib.md5(f"{business_data.get('business_name', '')}{time.time()}".encode()).hexdigest()[:12]
        
        conn = sqlite3.connect(self.db_path)
        c = conn.cursor()
        c.execute("""
            INSERT INTO whatsapp_clients 
            (id, business_name, category, phone_number_id, access_token, verify_token, 
             webhook_url, business_phone, address, active)
            VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, 1)
        """, (
            client_id,
            business_data.get("business_name", ""),
            business_data.get("category", ""),
            business_data.get("phone_number_id", ""),
            business_data.get("access_token", ""),
            business_data.get("verify_token", hashlib.md5(f"verify_{client_id}".encode()).hexdigest()[:16]),
            business_data.get("webhook_url", f"https://svoraj.me/webhook/whatsapp/{client_id}"),
            business_data.get("business_phone", ""),
            business_data.get("address", "")
        ))
        conn.commit()
        conn.close()
        return client_id
    
    def add_contact(self, client_id: str, contact_data: Dict) -> str:
        """Add a contact for a business."""
        contact_id = hashlib.md5(f"{client_id}{contact_data.get('phone', '')}{time.time()}".encode()).hexdigest()[:12]
        
        conn = sqlite3.connect(self.db_path)
        c = conn.cursor()
        c.execute("""
            INSERT INTO contacts 
            (id, client_id, name, phone, email, tags, custom_fields, opted_in, opted_in_at)
            VALUES (?, ?, ?, ?, ?, ?, ?, 1, CURRENT_TIMESTAMP)
        """, (
            contact_id,
            client_id,
            contact_data.get("name", ""),
            contact_data.get("phone", ""),
            contact_data.get("email", ""),
            json.dumps(contact_data.get("tags", [])),
            json.dumps(contact_data.get("custom_fields", {})),
        ))
        conn.commit()
        conn.close()
        return contact_id
    
    def send_template_message(self, client_id: str, contact_id: str, template_name: str, 
                              params: List[str], language: str = "it") -> Dict:
        """Send a template message via WhatsApp Business API."""
        # This would integrate with Meta Cloud API
        # For now, log the attempt
        conn = sqlite3.connect(self.db_path)
        c = conn.cursor()
        
        msg_id = hashlib.md5(f"{client_id}{contact_id}{template_name}{time.time()}".encode()).hexdigest()[:12]
        
        c.execute("""
            INSERT INTO messages 
            (id, conversation_id, client_id, contact_id, direction, message_type, 
             content, template_name, template_params, status, sent_at)
            VALUES (?, ?, ?, ?, 'outbound', 'template', ?, ?, ?, 'sent', CURRENT_TIMESTAMP)
        """, (
            msg_id,
            f"conv_{contact_id}",
            client_id,
            contact_id,
            f"Template: {template_name}",
            template_name,
            json.dumps(params),
        ))
        conn.commit()
        conn.close()
        
        # In production, here you would call Meta Cloud API:
        # POST https://graph.facebook.com/v18.0/{phone_number_id}/messages
        # Headers: Authorization: Bearer {access_token}
        # Body: {
        #     "messaging_product": "whatsapp",
        #     "to": "{contact_phone}",
        #     "type": "template",
        #     "template": {"name": template_name, "language": {"code": language}, "components": [...]}
        # }
        
        return {
            "message_id": msg_id,
            "status": "queued",
            "template": template_name
        }
    
    def create_broadcast(self, client_id: str, broadcast_data: Dict) -> str:
        """Create a broadcast campaign."""
        broadcast_id = hashlib.md5(f"{client_id}{broadcast_data.get('name', '')}{time.time()}".encode()).hexdigest()[:12]
        
        conn = sqlite3.connect(self.db_path)
        c = conn.cursor()
        c.execute("""
            INSERT INTO broadcasts 
            (id, client_id, name, template_name, template_params, audience_filter, 
             status, scheduled_at, created_at)
            VALUES (?, ?, ?, ?, ?, ?, 'draft', ?, CURRENT_TIMESTAMP)
        """, (
            broadcast_id,
            client_id,
            broadcast_data.get("name", ""),
            broadcast_data.get("template_name", ""),
            json.dumps(broadcast_data.get("template_params", [])),
            json.dumps(broadcast_data.get("audience_filter", {})),
            broadcast_data.get("scheduled_at", datetime.now().isoformat())
        ))
        conn.commit()
        conn.close()
        return broadcast_id

# ============================================================
# AUTOMATION FLOWS
# ============================================================

DEFAULT_FLOWS = {
    "booking_flow": {
        "name": "Prenotazione Appuntamento",
        "trigger": "keyword: prenota",
        "steps": [
            {"type": "ask", "field": "service", "prompt": "Quale servizio? (taglio, colore, barba, trattamento)"},
            {"type": "ask", "field": "date", "prompt": "Quando? (oggi, domani, lunedì, DD/MM)"},
            {"type": "ask", "field": "time", "prompt": "Che ora? (es. 14:30, 18:00)"},
            {"type": "confirm", "prompt": "Confermi: {service} il {date} alle {time}?"},
            {"type": "action", "action": "create_booking", "template": "booking_confirmation"}
        ]
    },
    "faq_flow": {
        "name": "FAQ Automatizzato",
        "trigger": "keyword: info",
        "steps": [
            {"type": "menu", "options": ["Orari e indirizzo", "Menu/Servizi", "Prenota", "Parla con umano"]},
            {"type": "branch", "field": "choice", "branches": {
                "1": {"type": "reply", "text": "Orari: Lun-Ven 9-19, Sab 9-13. Indirizzo: {address}"},
                "2": {"type": "reply", "text": "Menu/Servizi: {services_list}"},
                "3": {"type": "trigger", "flow": "booking_flow"},
                "4": {"type": "assign", "assignee": "human"}
            }}
        ]
    },
    "review_flow": {
        "name": "Richiesta Recensione Post-Visita",
        "trigger": "event: visit_completed",
        "delay_hours": 2,
        "steps": [
            {"type": "template", "template": "review_request", "params": ["{name}", "{business_name}", "{review_link}"]}
        ]
    },
    "birthday_flow": {
        "name": "Auguri Compleanno + Offerta",
        "trigger": "schedule: daily",
        "condition": "contact.birthday == today",
        "steps": [
            {"type": "template", "template": "birthday_offer", "params": ["{name}", "{business_name}", "{offer}", "{expiry_date}", "{booking_link}"]}
        ]
    },
    "loyalty_flow": {
        "name": "Programma Fedeltà",
        "trigger": "event: points_earned",
        "condition": "contact.points >= threshold",
        "steps": [
            {"type": "template", "template": "loyalty_reward", "params": ["{name}", "{points}", "{reward}", "{expiry_date}", "{business_name}"]}
        ]
    }
}

# ============================================================
# WEBHOOK HANDLER
# ============================================================

app = Flask(__name__)

@app.route("/webhook/whatsapp/<client_id>", methods=["GET", "POST"])
def whatsapp_webhook(client_id):
    """Handle incoming WhatsApp webhooks."""
    if request.method == "GET":
        # Verification
        mode = request.args.get("hub.mode")
        token = request.args.get("hub.verify_token")
        challenge = request.args.get("hub.challenge")
        
        # Verify token
        conn = sqlite3.connect(WHATSAPP_DB)
        c = conn.cursor()
        c.execute("SELECT verify_token FROM whatsapp_clients WHERE id=?", (client_id,))
        row = c.fetchone()
        conn.close()
        
        if row and token == row[0]:
            return challenge, 200
        return "Verification failed", 403
    
    elif request.method == "POST":
        # Process incoming message
        data = request.get_json()
        
        # Log webhook event
        conn = sqlite3.connect(WHATSAPP_DB)
        c = conn.cursor()
        c.execute("""
            INSERT INTO webhook_events (id, client_id, event_type, payload)
            VALUES (?, ?, ?, ?)
        """, (
            hashlib.md5(f"{client_id}{time.time()}".encode()).hexdigest()[:12],
            client_id,
            data.get("object", "unknown"),
            json.dumps(data)
        ))
        conn.commit()
        conn.close()
        
        # Process message asynchronously
        # For now, just acknowledge
        return "OK", 200

# ============================================================
# AUTOMATION ENGINE
# ============================================================

class AutomationEngine:
    def __init__(self):
        self.db_path = str(WHATSAPP_DB)
    
    def process_automations(self):
        """Process all active automations."""
        conn = sqlite3.connect(self.db_path)
        c = conn.cursor()
        
        # Get active automations
        c.execute("""
            SELECT * FROM automations WHERE active = 1
        """)
        automations = c.fetchall()
        conn.close()
        
        for automation in automations:
            # Process based on trigger type
            self._execute_automation(automation)
    
    def _execute_automation(self, automation):
        """Execute a single automation."""
        trigger_type = automation[3]  # trigger_type
        trigger_config = json.loads(automation[4]) if automation[4] else {}
        actions = json.loads(automation[5]) if automation[5] else []
        
        # Execute based on trigger type
        if trigger_type == "keyword":
            # Handled by webhook
            pass
        elif trigger_type == "schedule":
            # Check if it's time to run
            self._check_schedule(trigger_config)
        elif trigger_type == "event":
            # Triggered by webhook events
            pass
    
    def _check_schedule(self, config):
        """Check if scheduled automation should run."""
        # Implementation would check cron-like schedule
        pass

# ============================================================
# FLASK APP FOR WEBHOOKS
# ============================================================

whatsapp_crm = WhatsAppCRM()
automation_engine = AutomationEngine()

@app.route("/webhook/whatsapp/<client_id>", methods=["GET", "POST"])
def whatsapp_webhook(client_id):
    if request.method == "GET":
        # Verification
        mode = request.args.get("hub.mode")
        token = request.args.get("hub.verify_token")
        challenge = request.args.get("hub.challenge")
        
        conn = sqlite3.connect(WHATSAPP_DB)
        c = conn.cursor()
        c.execute("SELECT verify_token FROM whatsapp_clients WHERE id=?", (client_id,))
        row = c.fetchone()
        conn.close()
        
        if row and token == row[0]:
            return challenge, 200
        return "Verification failed", 403
    
    elif request.method == "POST":
        data = request.get_json()
        
        # Log webhook
        conn = sqlite3.connect(WHATSAPP_DB)
        c = conn.cursor()
        c.execute("""
            INSERT INTO webhook_events (id, client_id, event_type, payload)
            VALUES (?, ?, ?, ?)
        """, (
            hashlib.md5(f"{client_id}{time.time()}".encode()).hexdigest()[:12],
            client_id,
            data.get("object", "unknown"),
            json.dumps(data)
        ))
        conn.commit()
        conn.close()
        
        # Process inbound messages
        # In production, process asynchronously
        return "OK", 200

@app.route("/admin/whatsapp/clients", methods=["GET"])
def list_whatsapp_clients():
    conn = sqlite3.connect(WHATSAPP_DB)
    c = conn.cursor()
    c.execute("SELECT id, business_name, category, active FROM whatsapp_clients")
    clients = c.fetchall()
    conn.close()
    return jsonify({"clients": [dict(zip(["id", "business_name", "category", "active"], c)) for c in clients]})

@app.route("/admin/whatsapp/clients", methods=["POST"])
def create_whatsapp_client():
    data = request.get_json()
    client_id = whatsapp_crm.register_client(data)
    return jsonify({"client_id": client_id, "success": True})

@app.route("/admin/whatsapp/clients/<client_id>/contacts", methods=["POST"])
def add_contact(client_id):
    data = request.get_json()
    contact_id = whatsapp_crm.add_contact(client_id, data)
    return jsonify({"contact_id": contact_id, "success": True})

@app.route("/admin/whatsapp/clients/<client_id>/broadcast", methods=["POST"])
def create_broadcast(client_id):
    data = request.get_json()
    broadcast_id = whatsapp_crm.create_broadcast(client_id, data)
    return jsonify({"broadcast_id": broadcast_id, "success": True})

@app.route("/admin/whatsapp/clients/<client_id>/flows", methods=["GET"])
def list_flows(client_id):
    conn = sqlite3.connect(WHATSAPP_DB)
    c = conn.cursor()
    c.execute("SELECT * FROM bot_flows WHERE client_id=?", (client_id,))
    flows = c.fetchall()
    conn.close()
    return jsonify({"flows": [dict(zip(["id", "client_id", "name", "trigger", "flow_data", "active", "created_at"], f)) for f in flows]})

@app.route("/admin/whatsapp/clients/<client_id>/flows", methods=["POST"])
def create_flow(client_id):
    data = request.get_json()
    flow_id = hashlib.md5(f"{client_id}{data.get('name', '')}{time.time()}".encode()).hexdigest()[:12]
    
    conn = sqlite3.connect(WHATSAPP_DB)
    c = conn.cursor()
    c.execute("""
        INSERT INTO bot_flows (id, client_id, name, trigger, flow_data, active)
        VALUES (?, ?, ?, ?, ?, 1)
    """, (flow_id, client_id, data.get("name", ""), data.get("trigger", ""), json.dumps(data.get("flow_data", []))))
    conn.commit()
    conn.close()
    return jsonify({"flow_id": flow_id, "success": True})

# ============================================================
# MAIN EXECUTION
# ============================================================

def setup_whatsapp_crm():
    """Initialize WhatsApp CRM database and default flows."""
    print(f"\n{'='*60}")
    print(f" WHATSAPP CRM INITIALIZATION")
    print(f"{'='*60}\n")
    
    crm = WhatsAppCRM()
    
    # Register default flows
    conn = sqlite3.connect(WHATSAPP_DB)
    c = conn.cursor()
    
    for flow_key, flow_data in DEFAULT_FLOWS.items():
        flow_id = hashlib.md5(f"{flow_key}{time.time()}".encode()).hexdigest()[:12]
        c.execute("""
            INSERT OR IGNORE INTO bot_flows (id, name, trigger, flow_data, active)
            VALUES (?, ?, ?, ?, 1)
        """, (flow_id, flow_data["name"], flow_data["trigger"], json.dumps(flow_data["steps"])))
    
    conn.commit()
    conn.close()
    
    print("[+] WhatsApp CRM Database initialized")
    print(f"[+] Default flows registered: {list(DEFAULT_FLOWS.keys())}")
    print(f"[+] Database: {WHATSAPP_DB}")
    
    return True

if __name__ == "__main__":
    print("=== GHOST AGENCY - WHATSAPP CRM MVP ===\n")
    
    setup_whatsapp_crm()
    
    print(f"\n{'='*60}")
    print(f" WHATSAPP CRM READY")
    print(f"{'='*60}")
    print(f"Database: {WHATSAPP_DB}")
    print(f"Webhook endpoint: /webhook/whatsapp/<client_id>")
    print(f"Admin API: /admin/whatsapp/*")
    print(f"Default flows: {list(DEFAULT_FLOWS.keys())}")
    print(f"\nProssimo step: Configurare Meta Cloud API + templates approvati")
    print(f"Per clienti: registrazione via /admin/whatsapp/clients (POST)")