#!/usr/bin/env python3
"""
Ghost Agency - Gift Card Platform
Automated digital gift card creation, sales, delivery, redemption, and analytics
"""

import os
import json
import sqlite3
import hashlib
import time
import random
import string
import qrcode
from pathlib import Path
from datetime import datetime, timedelta
from typing import Dict, List, Any, Optional
from io import BytesIO
import base64

GIFTCARD_DB = Path("/home/ubuntu/GhostAgency") / "gift_card_platform.db"

# ============================================================
# GIFT CARD PLATFORM ENGINE
# ============================================================

class GiftCardPlatform:
    def __init__(self):
        self.db_path = str(GIFTCARD_DB)
        self.init_db()

    def init_db(self):
        conn = sqlite3.connect(self.db_path)
        c = conn.cursor()

        # Gift Card Products (templates)
        c.execute("""CREATE TABLE IF NOT EXISTS gift_card_products (
            id TEXT PRIMARY KEY,
            client_id TEXT NOT NULL,
            business_name TEXT,
            product_name TEXT,
            product_type TEXT,  -- amount, experience, package, subscription
            description TEXT,
            image_url TEXT,
            default_amount REAL,
            min_amount REAL,
            max_amount REAL,
            fixed_amounts TEXT,  -- JSON array: [10, 25, 50, 100]
            validity_days INTEGER DEFAULT 365,
            delivery_methods TEXT,  -- JSON: email, whatsapp, sms, print, qr, apple_wallet, google_wallet
            customizable_fields TEXT,  -- JSON: sender_name, recipient_name, message, occasion
            terms_conditions TEXT,
            status TEXT DEFAULT 'active',
            created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
            updated_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP
        )""")

        # Gift Cards (individual issued cards)
        c.execute("""CREATE TABLE IF NOT EXISTS gift_cards (
            id TEXT PRIMARY KEY,
            client_id TEXT NOT NULL,
            product_id TEXT NOT NULL,
            code TEXT UNIQUE,  -- human-readable code
            pin TEXT,  -- optional 4-digit PIN
            qr_code TEXT,  -- base64 encoded QR code
            amount REAL NOT NULL,
            currency TEXT DEFAULT 'EUR',
            status TEXT DEFAULT 'active',  -- active, redeemed, partially_redeemed, expired, cancelled, refunded
            purchaser_email TEXT,
            purchaser_name TEXT,
            purchaser_phone TEXT,
            recipient_email TEXT,
            recipient_name TEXT,
            recipient_phone TEXT,
            sender_message TEXT,
            occasion TEXT,  -- birthday, christmas, anniversary, thank_you, wedding, generic
            delivery_method TEXT,  -- email, whatsapp, sms, print, qr, apple_wallet, google_wallet
            delivery_status TEXT DEFAULT 'pending',  -- pending, sent, delivered, opened, failed
            delivered_at TIMESTAMP,
            opened_at TIMESTAMP,
            purchased_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
            redeemed_at TIMESTAMP,
            expires_at TIMESTAMP,
            balance REAL DEFAULT 0,
            original_amount REAL,
            metadata TEXT,  -- JSON for additional data
            created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
            updated_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP
        )""")

        # Transactions (redemptions, top-ups, refunds)
        c.execute("""CREATE TABLE IF NOT EXISTS gift_card_transactions (
            id TEXT PRIMARY KEY,
            gift_card_id TEXT NOT NULL,
            client_id TEXT NOT NULL,
            transaction_type TEXT,  -- purchase, redemption, top_up, refund, transfer, balance_check
            amount REAL,
            balance_before REAL,
            balance_after REAL,
            pos_transaction_id TEXT,
            pos_terminal_id TEXT,
            staff_id TEXT,
            location TEXT,
            notes TEXT,
            created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
            FOREIGN KEY (gift_card_id) REFERENCES gift_cards(id)
        )""")

        # Gift Card Campaigns
        c.execute("""CREATE TABLE IF NOT EXISTS gift_card_campaigns (
            id TEXT PRIMARY KEY,
            client_id TEXT NOT NULL,
            campaign_name TEXT,
            campaign_type TEXT,  -- seasonal, promotional, loyalty, referral_bonus, employee_gift
            product_ids TEXT,  -- JSON array
            discount_percent REAL DEFAULT 0,
            discount_fixed REAL DEFAULT 0,
            bonus_amount REAL DEFAULT 0,  -- buy 100 get 10 bonus
            target_audience TEXT,  -- all, vip, inactive, new_customers, employees
            channel TEXT,  -- email, whatsapp, sms, social, in_store, website
            template_id TEXT,
            start_date DATE,
            end_date DATE,
            budget REAL,
            status TEXT DEFAULT 'draft',  -- draft, scheduled, active, paused, completed
            sent_count INTEGER DEFAULT 0,
            redeemed_count INTEGER DEFAULT 0,
            revenue_generated REAL DEFAULT 0,
            created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
            updated_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP
        )""")

        # Campaign Sends
        c.execute("""CREATE TABLE IF NOT EXISTS gift_card_campaign_sends (
            id TEXT PRIMARY KEY,
            campaign_id TEXT NOT NULL,
            gift_card_id TEXT,
            recipient_email TEXT,
            recipient_phone TEXT,
            channel TEXT,
            sent_at TIMESTAMP,
            delivered_at TIMESTAMP,
            opened_at TIMESTAMP,
            clicked_at TIMESTAMP,
            purchased_at TIMESTAMP,
            status TEXT DEFAULT 'sent',  -- sent, delivered, opened, clicked, purchased, bounced
            created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
            FOREIGN KEY (campaign_id) REFERENCES gift_card_campaigns(id)
        )""")

        # Bulk Orders (B2B)
        c.execute("""CREATE TABLE IF NOT EXISTS bulk_orders (
            id TEXT PRIMARY KEY,
            client_id TEXT NOT NULL,
            company_name TEXT,
            contact_name TEXT,
            contact_email TEXT,
            contact_phone TEXT,
            product_id TEXT,
            quantity INTEGER,
            unit_amount REAL,
            total_amount REAL,
            discount_percent REAL DEFAULT 0,
            status TEXT DEFAULT 'quote',  -- quote, confirmed, paid, processing, shipped, delivered, cancelled
            delivery_method TEXT,  -- email_bulk, csv, api, physical_cards
            delivery_details TEXT,  -- JSON
            payment_status TEXT DEFAULT 'pending',  -- pending, paid, invoiced, refunded
            payment_method TEXT,
            invoice_number TEXT,
            notes TEXT,
            created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
            updated_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP
        )""")

        # Redemption Locations (for multi-location)
        c.execute("""CREATE TABLE IF NOT EXISTS redemption_locations (
            id TEXT PRIMARY KEY,
            client_id TEXT NOT NULL,
            location_name TEXT,
            address TEXT,
            phone TEXT,
            pos_system TEXT,  -- lightspeed, square, toast, clover, custom
            api_endpoint TEXT,
            api_key TEXT,
            active INTEGER DEFAULT 1,
            created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP
        )""")

        # Analytics
        c.execute("""CREATE TABLE IF NOT EXISTS gift_card_analytics (
            id TEXT PRIMARY KEY,
            client_id TEXT NOT NULL,
            date DATE,
            product_id TEXT,
            cards_sold INTEGER DEFAULT 0,
            cards_redeemed INTEGER DEFAULT 0,
            revenue REAL DEFAULT 0,
            redemption_value REAL DEFAULT 0,
            avg_card_value REAL DEFAULT 0,
            avg_redemption_value REAL DEFAULT 0,
            breakage_rate REAL DEFAULT 0,  -- unredeemed balance %
            new_customers_acquired INTEGER DEFAULT 0,
            repeat_redemption_rate REAL DEFAULT 0,
            created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP
        )""")

        # Apple/Google Wallet Passes
        c.execute("""CREATE TABLE IF NOT EXISTS wallet_passes (
            id TEXT PRIMARY KEY,
            gift_card_id TEXT NOT NULL,
            client_id TEXT NOT NULL,
            pass_type TEXT,  -- apple, google
            pass_serial_number TEXT,
            pass_json TEXT,  -- full pass JSON
            download_url TEXT,
            downloaded_at TIMESTAMP,
            installed_at TIMESTAMP,
            updated_at TIMESTAMP,
            status TEXT DEFAULT 'created',  -- created, downloaded, installed, uninstalled
            created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP
        )""")

        conn.commit()
        conn.close()

    def create_product(self, client_data: Dict, product_config: Dict) -> str:
        """Create a gift card product/template."""
        product_id = hashlib.md5(f"prod_{client_data.get('client_id', '')}{product_config.get('product_name', '')}{time.time()}".encode()).hexdigest()[:12]

        conn = sqlite3.connect(self.db_path)
        c = conn.cursor()
        c.execute("""
            INSERT INTO gift_card_products
            (id, client_id, business_name, product_name, product_type, description,
             image_url, default_amount, min_amount, max_amount, fixed_amounts,
             validity_days, delivery_methods, customizable_fields, terms_conditions, status)
            VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, 'active')
        """, (
            product_id,
            client_data.get("client_id", ""),
            client_data.get("business_name", ""),
            product_config.get("product_name", "Gift Card"),
            product_config.get("product_type", "amount"),
            product_config.get("description", "Regala un'esperienza unica"),
            product_config.get("image_url", ""),
            product_config.get("default_amount", 50),
            product_config.get("min_amount", 10),
            product_config.get("max_amount", 500),
            json.dumps(product_config.get("fixed_amounts", [10, 25, 50, 100, 200])),
            product_config.get("validity_days", 365),
            json.dumps(product_config.get("delivery_methods", ["email", "whatsapp", "print", "qr", "apple_wallet", "google_wallet"])),
            json.dumps(product_config.get("customizable_fields", ["sender_name", "recipient_name", "message", "occasion"])),
            product_config.get("terms_conditions", "Valido 12 mesi dall'acquisto. Non rimborsabile. Utilizzabile in una o più volte.")
        ))
        conn.commit()
        conn.close()
        return product_id

    def issue_gift_card(self, client_data: Dict, issue_data: Dict) -> Dict:
        """Issue a new gift card."""
        gift_card_id = hashlib.md5(f"gc_{client_data.get('client_id', '')}{issue_data.get('recipient_email', '')}{time.time()}".encode()).hexdigest()[:12]

        # Generate human-readable code
        code = self._generate_gift_card_code()
        pin = ''.join(random.choices(string.digits, k=4)) if issue_data.get("require_pin", False) else None

        # Get product details
        conn = sqlite3.connect(self.db_path)
        c = conn.cursor()
        c.execute("SELECT validity_days FROM gift_card_products WHERE id = ?", (issue_data.get("product_id"),))
        product = c.fetchone()
        validity_days = product[0] if product else 365

        amount = issue_data.get("amount", 50)
        expires_at = (datetime.now() + timedelta(days=validity_days)).isoformat()

        # Generate QR code
        qr_data = f"GIFTCARD:{code}:{amount}:EUR"
        qr_code_b64 = self._generate_qr_code(qr_data)

        c.execute("""
            INSERT INTO gift_cards
            (id, client_id, product_id, code, pin, qr_code, amount, currency, status,
             purchaser_email, purchaser_name, purchaser_phone,
             recipient_email, recipient_name, recipient_phone,
             sender_message, occasion, delivery_method, delivery_status,
             expires_at, balance, original_amount, created_at)
            VALUES (?, ?, ?, ?, ?, ?, ?, 'EUR', 'active',
                    ?, ?, ?, ?, ?, ?, ?, ?, ?, 'pending',
                    ?, ?, ?, CURRENT_TIMESTAMP)
        """, (
            gift_card_id,
            client_data.get("client_id", ""),
            issue_data.get("product_id", ""),
            code,
            pin,
            qr_code_b64,
            amount,
            issue_data.get("purchaser_email", ""),
            issue_data.get("purchaser_name", ""),
            issue_data.get("purchaser_phone", ""),
            issue_data.get("recipient_email", ""),
            issue_data.get("recipient_name", ""),
            issue_data.get("recipient_phone", ""),
            issue_data.get("sender_message", ""),
            issue_data.get("occasion", "generic"),
            issue_data.get("delivery_method", "email"),
            expires_at,
            amount,
            amount
        ))
        conn.commit()
        conn.close()

        return {
            "gift_card_id": gift_card_id,
            "code": code,
            "pin": pin,
            "qr_code": qr_code_b64,
            "amount": amount,
            "expires_at": expires_at,
            "status": "active"
        }

    def _generate_gift_card_code(self) -> str:
        """Generate a human-readable gift card code."""
        # Format: GC-XXXX-XXXX-XXXX
        parts = []
        for _ in range(4):
            part = ''.join(random.choices(string.ascii_uppercase + string.digits, k=4))
            parts.append(part)
        return f"GC-{'-'.join(parts)}"

    def _generate_qr_code(self, data: str) -> str:
        """Generate QR code as base64 string."""
        qr = qrcode.QRCode(version=1, box_size=10, border=4)
        qr.add_data(data)
        qr.make(fit=True)
        img = qr.make_image(fill_color="black", back_color="white")

        buffer = BytesIO()
        img.save(buffer, format="PNG")
        img_str = base64.b64encode(buffer.getvalue()).decode()
        return f"data:image/png;base64,{img_str}"

    def deliver_gift_card(self, gift_card_id: str, method: str = None) -> Dict:
        """Deliver a gift card via specified method."""
        conn = sqlite3.connect(self.db_path)
        c = conn.cursor()

        c.execute("SELECT * FROM gift_cards WHERE id = ?", (gift_card_id,))
        card = c.fetchone()

        if not card:
            conn.close()
            return {"error": "Gift card not found"}

        gc_id, client_id, product_id, code, pin, qr_code, amount, currency, status, \
        purchaser_email, purchaser_name, purchaser_phone, recipient_email, recipient_name, \
        recipient_phone, sender_message, occasion, delivery_method, delivery_status, \
        delivered_at, opened_at, purchased_at, redeemed_at, expires_at, balance, original_amount, metadata, created_at, updated_at = card

        if method is None:
            method = delivery_method

        # Simulate delivery
        delivery_result = {"method": method, "status": "sent", "delivered_at": datetime.now().isoformat()}

        if method == "email":
            delivery_result["details"] = f"Email sent to {recipient_email}"
        elif method == "whatsapp":
            delivery_result["details"] = f"WhatsApp sent to {recipient_phone}"
        elif method == "sms":
            delivery_result["details"] = f"SMS sent to {recipient_phone}"
        elif method == "print":
            delivery_result["details"] = "Print-ready PDF generated"
        elif method == "qr":
            delivery_result["details"] = "QR code image ready"
        elif method in ["apple_wallet", "google_wallet"]:
            delivery_result["details"] = f"Wallet pass generated for {method}"

        # Update card
        c.execute("""
            UPDATE gift_cards
            SET delivery_status = 'delivered', delivered_at = CURRENT_TIMESTAMP,
                delivery_method = ?
            WHERE id = ?
        """, (method, gift_card_id))

        conn.commit()
        conn.close()

        return delivery_result

    def redeem_gift_card(self, code: str, pin: str = None, amount: float = None, pos_data: Dict = None) -> Dict:
        """Redeem a gift card (full or partial)."""
        conn = sqlite3.connect(self.db_path)
        c = conn.cursor()

        c.execute("SELECT * FROM gift_cards WHERE code = ?", (code,))
        card = c.fetchone()

        if not card:
            conn.close()
            return {"error": "Invalid gift card code"}

        gc_id, client_id, product_id, gc_code, gc_pin, qr_code, amount, currency, status, \
        purchaser_email, purchaser_name, purchaser_phone, recipient_email, recipient_name, \
        recipient_phone, sender_message, occasion, delivery_method, delivery_status, \
        delivered_at, opened_at, purchased_at, redeemed_at, expires_at, balance, original_amount, metadata, created_at = card

        if status in ["redeemed", "expired", "cancelled", "refunded"]:
            conn.close()
            return {"error": f"Gift card is {status}"}

        if datetime.now() > datetime.fromisoformat(expires_at):
            c.execute("UPDATE gift_cards SET status = 'expired' WHERE id = ?", (gc_id,))
            conn.commit()
            conn.close()
            return {"error": "Gift card expired"}

        if gc_pin and pin and pin != gc_pin:
            conn.close()
            return {"error": "Invalid PIN"}

        current_balance = balance if balance > 0 else amount
        redeem_amount = amount if amount is None else min(amount, current_balance)

        if redeem_amount > current_balance:
            conn.close()
            return {"error": f"Insufficient balance. Available: {current_balance:.2f}€"}

        new_balance = current_balance - redeem_amount
        new_status = "redeemed" if new_balance <= 0 else "partially_redeemed"
        redeemed_at = datetime.now().isoformat() if new_balance <= 0 else None

        # Update gift card
        c.execute("""
            UPDATE gift_cards
            SET balance = ?, status = ?, redeemed_at = ?
            WHERE id = ?
        """, (new_balance, new_status, redeemed_at, gc_id))

        # Record transaction
        txn_id = hashlib.md5(f"txn_{gc_id}{time.time()}".encode()).hexdigest()[:12]
        c.execute("""
            INSERT INTO gift_card_transactions
            (id, gift_card_id, client_id, transaction_type, amount,
             balance_before, balance_after, pos_transaction_id, pos_terminal_id,
             staff_id, location, notes)
            VALUES (?, ?, ?, 'redemption', ?, ?, ?, ?, ?, ?, ?, ?)
        """, (
            txn_id, gc_id, client_id, redeem_amount,
            current_balance, new_balance,
            pos_data.get("transaction_id", "") if pos_data else "",
            pos_data.get("terminal_id", "") if pos_data else "",
            pos_data.get("staff_id", "") if pos_data else "",
            pos_data.get("location", "") if pos_data else "",
            pos_data.get("notes", "") if pos_data else ""
        ))

        conn.commit()
        conn.close()

        return {
            "success": True,
            "gift_card_id": gc_id,
            "code": code,
            "redeemed_amount": redeem_amount,
            "remaining_balance": new_balance,
            "status": new_status,
            "currency": currency
        }

    def check_balance(self, code: str, pin: str = None) -> Dict:
        """Check gift card balance."""
        conn = sqlite3.connect(self.db_path)
        c = conn.cursor()

        c.execute("SELECT * FROM gift_cards WHERE code = ?", (code,))
        card = c.fetchone()
        conn.close()

        if not card:
            return {"error": "Invalid gift card code"}

        gc_id, client_id, product_id, gc_code, gc_pin, qr_code, amount, currency, status, \
        purchaser_email, purchaser_name, purchaser_phone, recipient_email, recipient_name, \
        recipient_phone, sender_message, occasion, delivery_method, delivery_status, \
        delivered_at, opened_at, purchased_at, redeemed_at, expires_at, balance, original_amount, metadata, created_at = card

        if gc_pin and pin and pin != gc_pin:
            return {"error": "Invalid PIN"}

        current_balance = balance if balance > 0 else amount
        is_expired = datetime.now() > datetime.fromisoformat(expires_at)

        return {
            "code": code,
            "balance": current_balance,
            "original_amount": original_amount,
            "currency": currency,
            "status": status,
            "expires_at": expires_at,
            "is_expired": is_expired,
            "recipient_name": recipient_name,
            "sender_message": sender_message,
            "occasion": occasion
        }

    def create_campaign(self, client_data: Dict, campaign_config: Dict) -> str:
        """Create a gift card marketing campaign."""
        campaign_id = hashlib.md5(f"camp_{client_data.get('client_id', '')}{campaign_config.get('campaign_name', '')}{time.time()}".encode()).hexdigest()[:12]

        conn = sqlite3.connect(self.db_path)
        c = conn.cursor()
        c.execute("""
            INSERT INTO gift_card_campaigns
            (id, client_id, campaign_name, campaign_type, product_ids, discount_percent,
             discount_fixed, bonus_amount, target_audience, channel, template_id,
             start_date, end_date, budget, status)
            VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, 'draft')
        """, (
            campaign_id,
            client_data.get("client_id", ""),
            campaign_config.get("campaign_name", "Campagna Gift Card"),
            campaign_config.get("campaign_type", "seasonal"),
            json.dumps(campaign_config.get("product_ids", [])),
            campaign_config.get("discount_percent", 0),
            campaign_config.get("discount_fixed", 0),
            campaign_config.get("bonus_amount", 0),
            campaign_config.get("target_audience", "all"),
            campaign_config.get("channel", "email"),
            campaign_config.get("template_id", ""),
            campaign_config.get("start_date", datetime.now().date().isoformat()),
            campaign_config.get("end_date", (datetime.now() + timedelta(days=30)).date().isoformat()),
            campaign_config.get("budget", 1000)
        ))
        conn.commit()
        conn.close()
        return campaign_id

    def generate_wallet_pass(self, gift_card_id: str, pass_type: str = "apple") -> Dict:
        """Generate Apple Wallet / Google Wallet pass."""
        conn = sqlite3.connect(self.db_path)
        c = conn.cursor()

        c.execute("SELECT * FROM gift_cards WHERE id = ?", (gift_card_id,))
        card = c.fetchone()

        if not card:
            conn.close()
            return {"error": "Gift card not found"}

        gc_id, client_id, product_id, code, pin, qr_code, amount, currency, status, \
        purchaser_email, purchaser_name, purchaser_phone, recipient_email, recipient_name, \
        recipient_phone, sender_message, occasion, delivery_method, delivery_status, \
        delivered_at, opened_at, purchased_at, redeemed_at, expires_at, balance, original_amount, metadata, created_at, updated_at = card

        # Generate pass JSON
        pass_data = {
            "formatVersion": 1,
            "passTypeIdentifier": f"pass.com.svoraj.giftcard.{client_id}",
            "serialNumber": code,
            "teamIdentifier": "TEAM_ID",
            "organizationName": recipient_name or "Gift Card",
            "description": f"Gift Card {code}",
            "logoText": "Gift Card",
            "foregroundColor": "rgb(255, 255, 255)",
            "backgroundColor": "rgb(59, 130, 246)",
            "labelColor": "rgb(255, 255, 255)",
            "storeCard": {
                "headerFields": [
                    {"key": "balance", "label": "SALDO", "value": f"{balance if balance > 0 else amount:.2f} €"}
                ],
                "primaryFields": [
                    {"key": "code", "label": "CODICE", "value": code}
                ],
                "secondaryFields": [
                    {"key": "expires", "label": "SCADENZA", "value": expires_at[:10]},
                    {"key": "sender", "label": "DA", "value": purchaser_name or "Un amico"}
                ],
                "auxiliaryFields": [
                    {"key": "message", "label": "MESSAGGIO", "value": sender_message or "Buon divertimento!"}
                ],
                "barcode": {
                    "format": "PKBarcodeFormatQR",
                    "message": f"GIFTCARD:{code}:{amount}:EUR",
                    "messageEncoding": "iso-8859-1"
                }
            }
        }

        pass_json = json.dumps(pass_data)

        pass_id = hashlib.md5(f"wallet_{gc_id}{pass_type}{time.time()}".encode()).hexdigest()[:12]
        download_url = f"https://svoraj.me/wallet/{pass_id}.pkpass"

        c.execute("""
            INSERT INTO wallet_passes
            (id, gift_card_id, client_id, pass_type, pass_serial_number, pass_json,
             download_url, status)
            VALUES (?, ?, ?, ?, ?, ?, ?, 'created')
        """, (
            pass_id, gc_id, client_id, pass_type, code, pass_json, download_url
        ))

        conn.commit()
        conn.close()

        return {
            "pass_id": pass_id,
            "download_url": download_url,
            "pass_type": pass_type,
            "serial_number": code
        }

    def get_analytics(self, client_id: str, days: int = 30) -> Dict:
        """Get gift card analytics."""
        conn = sqlite3.connect(self.db_path)
        c = conn.cursor()

        start_date = (datetime.now() - timedelta(days=days)).date().isoformat()

        # Sales
        c.execute("""
            SELECT COUNT(*), SUM(amount), AVG(amount)
            FROM gift_cards
            WHERE client_id = ? AND purchased_at >= ?
        """, (client_id, start_date))
        sales = c.fetchone()

        # Redemptions
        c.execute("""
            SELECT COUNT(*), SUM(amount), AVG(amount)
            FROM gift_card_transactions
            WHERE client_id = ? AND created_at >= ? AND transaction_type = 'redemption'
        """, (client_id, start_date))
        redemptions = c.fetchone()

        # Breakage (unredeemed balance on expired cards)
        c.execute("""
            SELECT COUNT(*), SUM(balance)
            FROM gift_cards
            WHERE client_id = ? AND status = 'expired' AND balance > 0
        """, (client_id,))
        breakage = c.fetchone()

        # Outstanding liability
        c.execute("""
            SELECT COUNT(*), SUM(balance)
            FROM gift_cards
            WHERE client_id = ? AND status IN ('active', 'partially_redeemed') AND balance > 0
        """, (client_id,))
        liability = c.fetchone()

        conn.close()

        return {
            "period_days": days,
            "cards_sold": sales[0] or 0,
            "total_sales": sales[1] or 0,
            "avg_card_value": sales[2] or 0,
            "cards_redeemed": redemptions[0] or 0,
            "total_redemption_value": redemptions[1] or 0,
            "avg_redemption_value": redemptions[2] or 0,
            "redemption_rate": round((redemptions[0] or 0) / (sales[0] or 1) * 100, 1),
            "expired_cards": breakage[0] or 0,
            "breakage_value": breakage[1] or 0,
            "active_cards": liability[0] or 0,
            "outstanding_liability": liability[1] or 0
        }


def run_gift_card_platform():
    print(f"\n{'='*60}")
    print(f" GIFT CARD PLATFORM")
    print(f"{'='*60}\n")

    platform = GiftCardPlatform()

    conn = sqlite3.connect("/home/ubuntu/GhostAgency/lead_broker.db")
    c = conn.cursor()
    c.execute("""
        SELECT id, nome, categoria, citta, email, telefono
        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 gift card platform for {len(leads)} leads...")

    total_products = 0
    total_cards = 0
    total_campaigns = 0

    for lead in leads:
        lead_id, nome, categoria, citta, email, telefono = lead

        client_data = {
            "client_id": lead_id,
            "business_name": nome,
            "category": categoria,
            "location": citta,
            "email": email,
            "phone": telefono
        }

        # Create gift card products
        products_config = [
            {
                "product_name": f"Gift Card {nome}",
                "product_type": "amount",
                "description": f"Regala un'esperienza da {nome}",
                "default_amount": 50,
                "min_amount": 10,
                "max_amount": 500,
                "fixed_amounts": [10, 25, 50, 100, 200],
                "validity_days": 365,
                "delivery_methods": ["email", "whatsapp", "sms", "print", "qr", "apple_wallet", "google_wallet"]
            },
            {
                "product_name": f"Cena per Due - {nome}",
                "product_type": "experience",
                "description": f"Cena completa per due persone da {nome}",
                "default_amount": 80,
                "min_amount": 80,
                "max_amount": 80,
                "fixed_amounts": [80],
                "validity_days": 180
            }
        ]

        for prod_config in products_config:
            platform.create_product(client_data, prod_config)
            total_products += 1

        # Issue sample gift cards
        for _ in range(random.randint(20, 100)):
            issue_data = {
                "product_id": "prod_1",
                "amount": random.choice([25, 50, 80, 100, 150]),
                "purchaser_email": f"buyer_{random.randint(1, 1000)}@example.com",
                "purchaser_name": f"Acquirente {random.randint(1, 100)}",
                "recipient_email": f"gift_{random.randint(1, 10000)}@example.com",
                "recipient_name": f"Destinatario {random.randint(1, 100)}",
                "sender_message": random.choice(["Buon compleanno!", "Grazie di tutto!", "Per te!", "Buone feste!", "Te lo meriti!"]),
                "occasion": random.choice(["birthday", "christmas", "anniversary", "thank_you", "wedding", "generic"]),
                "delivery_method": random.choice(["email", "whatsapp", "print", "qr", "apple_wallet"])
            }
            result = platform.issue_gift_card(client_data, issue_data)
            if "error" not in result:
                total_cards += 1
                # Deliver some
                if random.random() < 0.8:
                    platform.deliver_gift_card(result["gift_card_id"])

        # Create campaigns
        campaign_configs = [
            {"campaign_name": "Natale 2024", "campaign_type": "seasonal", "discount_percent": 10, "bonus_amount": 10},
            {"campaign_name": "San Valentino", "campaign_type": "seasonal", "discount_percent": 15},
            {"campaign_name": "Festa della Mamma", "campaign_type": "seasonal", "bonus_amount": 5},
            {"campaign_name": "Employee Gifts", "campaign_type": "employee_gift", "target_audience": "employees"}
        ]
        for camp_config in campaign_configs:
            platform.create_campaign(client_data, camp_config)
            total_campaigns += 1

        # Get analytics
        analytics = platform.get_analytics(lead_id, days=30)

        print(f"   [+] {nome} ({categoria}) - Prodotti: 2 | Carte emesse: {analytics['cards_sold']} | Vendite: {analytics['total_sales']:.0f}€ | Riscosse: {analytics['cards_redeemed']} | Redemption rate: {analytics['redemption_rate']}% | Liability: {analytics['outstanding_liability']:.0f}€")

    print(f"\n[+] Gift Card Platform setup complete")
    print(f"[+] Total products created: {total_products}")
    print(f"[+] Total gift cards issued: {total_cards}")
    print(f"[+] Total campaigns created: {total_campaigns}")
    print(f"[+] Features: QR codes, Apple/Google Wallet, partial redemption, bulk orders, breakage tracking")
    print(f"[+] Next: POS integration (Lightspeed, Square, Toast), Stripe for payments, email/WhatsApp delivery automation")

if __name__ == "__main__":
    run_gift_card_platform()