#!/usr/bin/env python3
"""
SAGE Product Catalog - All Services, One-Click Purchase
Everything Eden can do, available for instant buy
"""
import json
import hashlib
import sqlite3
from datetime import datetime
from pathlib import Path
from typing import Dict, List, Optional

# Product Catalog - EVERYTHING
SAGE_PRODUCTS = {
    # === CODE REVIEW TIERS ===
    "review_single": {
        "name": "Single File Review",
        "category": "code_review", 
        "price": 25,
        "description": "AI-powered review of one file with security, performance, and quality analysis",
        "deliverable": "JSON report + recommendations"
    },
    "review_pr": {
        "name": "Pull Request Review",
        "category": "code_review",
        "price": 50,
        "description": "Full PR analysis with line-by-line comments and approval recommendation",
        "deliverable": "PR comments + summary report"
    },
    "review_repo": {
        "name": "Full Repository Audit",
        "category": "code_review",
        "price": 200,
        "description": "Complete codebase analysis - architecture, security, tech debt, performance",
        "deliverable": "Comprehensive audit report + prioritized fixes"
    },
    
    # === CODE GENERATION ===
    "gen_function": {
        "name": "Function Generator",
        "category": "code_generation",
        "price": 15,
        "description": "Generate a single function/method from description",
        "deliverable": "Working code + tests"
    },
    "gen_module": {
        "name": "Module Generator", 
        "category": "code_generation",
        "price": 75,
        "description": "Generate complete module/class with full functionality",
        "deliverable": "Production-ready module + documentation"
    },
    "gen_feature": {
        "name": "Feature Generator",
        "category": "code_generation",
        "price": 150,
        "description": "End-to-end feature implementation across your codebase",
        "deliverable": "Complete feature + tests + integration guide"
    },
    "gen_project": {
        "name": "Project Scaffolding",
        "category": "code_generation",
        "price": 300,
        "description": "Full project setup with architecture, CI/CD, testing framework",
        "deliverable": "Complete project skeleton ready for development"
    },
    
    # === DEBUGGING ===
    "debug_issue": {
        "name": "Bug Analysis",
        "category": "debugging",
        "price": 35,
        "description": "Root cause analysis of a specific bug/issue",
        "deliverable": "Diagnosis + fix + prevention recommendations"
    },
    "debug_crash": {
        "name": "Crash Investigation",
        "category": "debugging",
        "price": 75,
        "description": "Deep dive into crashes, memory issues, race conditions",
        "deliverable": "Full crash analysis + fix + monitoring setup"
    },
    "debug_performance": {
        "name": "Performance Debugging",
        "category": "debugging",
        "price": 100,
        "description": "Find and fix performance bottlenecks",
        "deliverable": "Profiling report + optimizations + before/after metrics"
    },
    
    # === SECURITY ===
    "security_scan": {
        "name": "Security Scan",
        "category": "security",
        "price": 100,
        "description": "Vulnerability scan with OWASP top 10 coverage",
        "deliverable": "Security report + severity rankings + remediation"
    },
    "security_audit": {
        "name": "Security Audit",
        "category": "security",
        "price": 500,
        "description": "Comprehensive security assessment + penetration testing recommendations",
        "deliverable": "Full audit report + compliance checklist"
    },
    
    # === SUBSCRIPTION TIERS ===
    "monthly_basic": {
        "name": "SAGE Basic Monthly",
        "category": "subscription",
        "price": 50,
        "interval": "month",
        "description": "5 reviews + 3 generations per month",
        "deliverable": "Monthly allocation + priority support"
    },
    "monthly_pro": {
        "name": "SAGE Pro Monthly",
        "category": "subscription",
        "price": 150,
        "interval": "month",
        "description": "Unlimited reviews + 10 generations + debugging",
        "deliverable": "Full access + 24hr response"
    },
    "monthly_enterprise": {
        "name": "SAGE Enterprise Monthly",
        "category": "subscription",
        "price": 500,
        "interval": "month",
        "description": "Everything unlimited + dedicated instance + custom integrations",
        "deliverable": "White-glove service + SLA"
    },
    
    # === MAX CAPITAL - EVERYTHING ===
    "max_capital": {
        "name": "SAGE MAX CAPITAL",
        "category": "ultimate",
        "price": 1000,
        "interval": "month",
        "description": "EVERYTHING. Unlimited reviews, generation, debugging, security, priority everything.",
        "deliverable": "Full SAGE suite + dedicated support + custom development hours",
        "includes": ["review_repo", "gen_project", "debug_performance", "security_audit", "monthly_enterprise"]
    },
    
    # === ONE-TIME CONSULTING ===
    "consulting_hour": {
        "name": "Consulting Hour",
        "category": "consulting",
        "price": 150,
        "description": "1-on-1 architecture/code consultation",
        "deliverable": "Live session + notes + action items"
    },
    "consulting_day": {
        "name": "Consulting Day",
        "category": "consulting",
        "price": 1000,
        "description": "Full day engagement - architecture review, planning, implementation guidance",
        "deliverable": "Full day + comprehensive documentation"
    }
}


class SageProductCatalog:
    """Manage SAGE products and purchases"""
    
    def __init__(self, db_path="/Eden/DATA/sales.db"):
        self.db_path = Path(db_path)
        self.products = SAGE_PRODUCTS
        self.paypal_email = "jamlen@hotmail.ca"
        self._init_db()
        
    def _init_db(self):
        """Initialize products and orders tables"""
        conn = sqlite3.connect(self.db_path)
        c = conn.cursor()
        
        c.execute("""CREATE TABLE IF NOT EXISTS products (
            id TEXT PRIMARY KEY,
            name TEXT,
            category TEXT,
            price REAL,
            description TEXT,
            active INTEGER DEFAULT 1
        )""")
        
        c.execute("""CREATE TABLE IF NOT EXISTS orders (
            id TEXT PRIMARY KEY,
            product_id TEXT,
            customer_email TEXT,
            amount REAL,
            status TEXT DEFAULT 'pending',
            payment_method TEXT,
            payment_id TEXT,
            created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
            completed_at TIMESTAMP,
            FOREIGN KEY(product_id) REFERENCES products(id)
        )""")
        
        # Sync products to DB
        for prod_id, prod in self.products.items():
            c.execute("""INSERT OR REPLACE INTO products (id, name, category, price, description)
                        VALUES (?, ?, ?, ?, ?)""",
                     (prod_id, prod['name'], prod['category'], prod['price'], prod['description']))
        
        conn.commit()
        conn.close()
        
    def get_all_products(self) -> Dict:
        """Get full product catalog"""
        return self.products
    
    def get_by_category(self, category: str) -> Dict:
        """Get products in a category"""
        return {k: v for k, v in self.products.items() if v['category'] == category}
    
    def get_product(self, product_id: str) -> Optional[Dict]:
        """Get single product details"""
        return self.products.get(product_id)
    
    def generate_order_id(self, product_id: str, email: str) -> str:
        """Generate unique order ID"""
        data = f"{product_id}{email}{datetime.now().isoformat()}"
        return hashlib.sha256(data.encode()).hexdigest()[:16].upper()
    
    def create_order(self, product_id: str, customer_email: str) -> Dict:
        """Create a new order"""
        product = self.get_product(product_id)
        if not product:
            return {"error": f"Product {product_id} not found"}
            
        order_id = self.generate_order_id(product_id, customer_email)
        
        conn = sqlite3.connect(self.db_path)
        c = conn.cursor()
        c.execute("""INSERT INTO orders (id, product_id, customer_email, amount, status, payment_method)
                    VALUES (?, ?, ?, ?, 'pending', 'paypal')""",
                 (order_id, product_id, customer_email, product['price']))
        conn.commit()
        conn.close()
        
        return {
            "order_id": order_id,
            "product": product['name'],
            "amount": product['price'],
            "payment_link": self.generate_paypal_link(order_id, product),
            "status": "pending"
        }
    
    def generate_paypal_link(self, order_id: str, product: Dict) -> str:
        """Generate PayPal.me payment link"""
        amount = product['price']
        # PayPal.me direct link
        return f"https://paypal.me/jamlen/{amount}USD?order={order_id}"
    
    def complete_order(self, order_id: str, payment_id: str = None):
        """Mark order as completed"""
        conn = sqlite3.connect(self.db_path)
        c = conn.cursor()
        c.execute("""UPDATE orders SET status = 'completed', payment_id = ?, completed_at = CURRENT_TIMESTAMP
                    WHERE id = ?""", (payment_id, order_id))
        conn.commit()
        conn.close()
        
    def get_revenue_stats(self) -> Dict:
        """Get revenue statistics"""
        conn = sqlite3.connect(self.db_path)
        c = conn.cursor()
        
        c.execute("SELECT SUM(amount) FROM orders WHERE status = 'completed'")
        total = c.fetchone()[0] or 0
        
        c.execute("SELECT COUNT(*) FROM orders WHERE status = 'completed'")
        completed = c.fetchone()[0]
        
        c.execute("SELECT COUNT(*) FROM orders WHERE status = 'pending'")
        pending = c.fetchone()[0]
        
        conn.close()
        
        return {
            "total_revenue": total,
            "completed_orders": completed,
            "pending_orders": pending
        }
    
    def print_catalog(self):
        """Print formatted product catalog"""
        print("=" * 70)
        print("  SAGE PRODUCT CATALOG - ALL SERVICES")
        print("=" * 70)
        
        categories = {}
        for pid, prod in self.products.items():
            cat = prod['category']
            if cat not in categories:
                categories[cat] = []
            categories[cat].append((pid, prod))
        
        for cat, prods in categories.items():
            print(f"\n### {cat.upper().replace('_', ' ')} ###")
            for pid, prod in prods:
                interval = f"/{prod.get('interval', 'once')}" if 'interval' in prod else ""
                print(f"  [{pid}] {prod['name']}: ${prod['price']}{interval}")
                print(f"      {prod['description'][:60]}...")
        
        print("\n" + "=" * 70)
        print("  ONE-CLICK BUY: catalog.create_order('product_id', 'email@example.com')")
        print("=" * 70)


def main():
    """Demo the product catalog"""
    catalog = SageProductCatalog()
    catalog.print_catalog()
    
    # Show stats
    stats = catalog.get_revenue_stats()
    print(f"\n[REVENUE STATS]")
    print(f"  Total Revenue: ${stats['total_revenue']:.2f}")
    print(f"  Completed: {stats['completed_orders']}")
    print(f"  Pending: {stats['pending_orders']}")
    
    # Example order
    print("\n[EXAMPLE ORDER]")
    order = catalog.create_order("max_capital", "customer@example.com")
    print(f"  Order ID: {order.get('order_id')}")
    print(f"  Product: {order.get('product')}")
    print(f"  Amount: ${order.get('amount')}")
    print(f"  Payment Link: {order.get('payment_link')}")


if __name__ == "__main__":
    main()
