# File: /Users/bpa/Desktop/ForesixaQuant/local_payment_server.py
# Configuration: Hardened E-Commerce Payment Gateway Server v1.5
import argparse
import asyncio
import json
import sqlite3
from pathlib import Path
from aiohttp import web

class ForesixaPaymentServer:
    def __init__(self, root_path):
        self.root_path = Path(root_path)
        self.db_path = self.root_path / "supervisor.db"
        self._initialize_payment_ledger()

    def _initialize_payment_ledger(self):
        conn = sqlite3.connect(self.db_path)
        cursor = conn.cursor()
        cursor.execute("""
            CREATE TABLE IF NOT EXISTS customer_orders (
                order_id TEXT PRIMARY KEY,
                stripe_session_id TEXT,
                customer_email TEXT,
                product_delivered TEXT,
                payment_status TEXT
            )
        """)
        conn.commit()
        conn.close()

    async def handle_root_health(self, request):
        return web.json_response({
            "storefront_status": "ONLINE",
            "service": "etv_payment_gateway",
            "version": "1.5.0"
        })

    async def handle_order_lookup(self, request):
        order_id = request.query.get("order_id")
        if not order_id:
            return web.json_response({"error": "Missing order_id parameters"}, status=400)

        conn = sqlite3.connect(self.db_path)
        cursor = conn.cursor()
        cursor.execute("SELECT order_id, product_delivered, payment_status FROM customer_orders WHERE order_id = ?", (order_id,))
        row = cursor.fetchone()
        conn.close()

        if not row:
            return web.json_response({
                "order_id": order_id,
                "payment_status": "UNPAID",
                "product_delivered": "NOT_FULFILLED",
                "message": "Order reference not found in production system registries."
            }, status=404)

        return web.json_response({
            "order_id": row[0],
            "product_delivered": row[1],
            "payment_status": row[2]
        })

    async def handle_stripe_webhook(self, request):
        try:
            payload = await request.text()
            event = json.loads(payload)
        except Exception as e:
            return web.json_response({"error": f"Invalid webhook: {e}"}, status=400)

        if event.get("type") == "checkout.session.completed":
            session = event.get("data", {}).get("object", {})
            order_id = session.get("client_reference_id", "MOCK_ORDER_123")
            customer_email = session.get("customer_details", {}).get("email", "customer@sotality.com")
            
            print(f"📥 [STRIPE WEBHOOK] Successful checkout detected for Order {order_id}")

            conn = sqlite3.connect(self.db_path)
            cursor = conn.cursor()
            cursor.execute("""
                INSERT OR REPLACE INTO customer_orders (order_id, stripe_session_id, customer_email, product_delivered, payment_status)
                VALUES (?, ?, ?, ?, ?)
            """, (order_id, session.get("id"), customer_email, "VERIFIED_COURSE_DELIVERED", "PAID"))
            conn.commit()
            conn.close()
            print(f"🏆 [DELIVERY] Product successfully released to user storage rails.")

        return web.Response(text="WEBHOOK_PROCESSED_COMPLIANT", status=200)

def main():
    p = argparse.ArgumentParser()
    p.add_argument('--root', type=Path, default=Path('/Users/bpa/Desktop/ForesixaQuant'))
    p.add_argument('--host', default='0.0.0.0')
    p.add_argument('--port', type=int, default=8766)
    args = p.parse_args()

    server = ForesixaPaymentServer(args.root)
    app = web.Application()
    
    app.router.add_get('/', server.handle_root_health)
    app.router.add_get('/health', server.handle_root_health)
    app.router.add_get('/order', server.handle_order_lookup)
    app.router.add_post('/webhook/stripe', server.handle_stripe_webhook)

    print(f"\n============================================================")
    print(f"   FORESIXA STOREFRONT PAYMENT CORE: ONLINE                 ")
    print(f"============================================================")
    web.run_app(app, host=args.host, port=args.port)

if __name__ == '__main__':
    main()
