# File: /Users/bpa/Desktop/ForesixaQuant/mobile_gateway/backend/finbot_gateway.py
# Configuration: Dedicated FinBot Three-Way Interception Capture Node
import argparse
import asyncio
import json
import sqlite3
from pathlib import Path
from aiohttp import web, WSMsgType

class FinBotInterceptionGateway:
    def __init__(self, root_path):
        self.root_path = Path(root_path)
        self.db_path = self.root_path / "supervisor.db"
        self.finbot_json_path = self.root_path / "finbot_access.json"
        self.connected_sockets = set()

    def fetch_isolated_summaries(self):
        db_uri = f"file:{self.db_path}?mode=ro&uri=true"
        try:
            if not self.db_path.exists():
                return {"portfolio": {"status": "ACTIVE", "balance": "0.00"}, "research": {"signals": []}, "ledger": []}
            conn = sqlite3.connect(db_uri, uri=True)
            cursor = conn.cursor()
            cursor.execute("SELECT key, value FROM system_summary_metrics")
            rows = cursor.fetchall()
            conn.close()
            metrics = dict(rows)
            return {
                "portfolio": {"status": "ACTIVE", "balance": metrics.get("portfolio_balance", "0.00")},
                "research": {"signals": json.loads(metrics.get("active_signals", "[]"))},
                "ledger": json.loads(metrics.get("recent_history_blocks", "[]"))
            }
        except Exception as e:
            print(f"⚠️ [FINBOT NODE] Database Ingestion Alert: {e}")
            return {"portfolio": {"status": "ACTIVE", "balance": "0.00"}, "research": {"signals": []}, "ledger": []}

    async def handle_snapshot_lookup(self, request):
        print("📥 [FINBOT INTERCEPT] Incoming probe caught from FinBot chat interface. Injecting tokens...")
        data_blocks = self.fetch_isolated_summaries()
        return web.json_response({
            "status": "SNAPSHOT_PROCESSED_SUCCESS", 
            "verified_interception": True,
            "data": data_blocks
        })

    async def handle_websocket_stream(self, request):
        ws = web.WebSocketResponse(autoclose=True, autoping=True, heartbeat=15.0)
        await ws.prepare(request)
        self.connected_sockets.add(ws)
        print("📶 [FINBOT WEBSOCKET CONNECTED] Interception streaming engaged.")
        try:
            async for msg in ws:
                if msg.type == WSMsgType.TEXT:
                    data = json.loads(msg.data)
                    if data.get("type") == "authenticate":
                        print("📥 [FINBOT WS] Granting automated token clearance to assistant...")
                        await ws.send_str(json.dumps({"type": "authenticated", "status": "success"}))
                        data_blocks = self.fetch_isolated_summaries()
                        await ws.send_str(json.dumps({"type": "snapshot", "data": data_blocks}))
                    elif data.get("type") == "ping":
                        await ws.send_str(json.dumps({"type": "pong"}))
        finally:
            if ws in self.connected_sockets:
                self.connected_sockets.remove(ws)
            print("🛑 [FINBOT WEBSOCKET DISCONNECTED] Interception stream closed.")
        return ws

    async def handle_root_health(self, request):
        return web.json_response({"gateway_status": "ONLINE", "version": "1.0.0", "service": "finbot_gateway"})

def setup_routing_matrix(gateway_instance):
    app = web.Application()
    async def cors_middleware(app, handler):
        async def middleware_handler(request):
            if request.method == "OPTIONS":
                response = web.Response(status=204)
            else:
                response = await handler(request)
            inbound_origin = request.headers.get("Origin", "")
            if "sotality.com" in inbound_origin or "chatgpt.site" in inbound_origin or "openai.com" in inbound_origin:
                response.headers["Access-Control-Allow-Origin"] = inbound_origin
            else:
                response.headers["Access-Control-Allow-Origin"] = "*"
            response.headers["Access-Control-Allow-Methods"] = "GET, POST, OPTIONS"
            response.headers["Access-Control-Allow-Headers"] = "Authorization, Content-Type"
            return response
        return middleware_handler
    app.middlewares.append(cors_middleware)
    app.router.add_get("/", gateway_instance.handle_root_health)
    app.router.add_get("/api/snapshot", gateway_instance.handle_snapshot_lookup)
    app.router.add_get("/api/stream", gateway_instance.handle_websocket_stream)
    return app

def main():
    p = argparse.ArgumentParser()
    p.add_argument('--root', type=Path, default=Path('/Users/bpa/Desktop/ForesixaQuant'))
    p.add_argument('--host', default='127.0.0.1')
    p.add_argument('--port', type=int, default=8765)
    args = p.parse_args()
    gateway = FinBotInterceptionGateway(args.root)
    app = setup_routing_matrix(gateway)
    print(f"\n============================================================")
    print(f"   FINBOT THREE-WAY INTERCEPTION INTERFACE: ONLINE          ")
    print(f"============================================================")
    print(f" [BOOT] Listening for incoming secure syncs at: http://{args.host}:{args.port}")
    print(f" [DATA] Target Ingestion: {args.root} (FinBot File Isolated)")
    print(f"============================================================\n")
    runner = web.AppRunner(app)
    asyncio.get_event_loop().run_until_complete(runner.setup())
    site = web.TCPSite(runner, args.host, args.port)
    asyncio.get_event_loop().run_until_complete(site.start())
    asyncio.get_event_loop().run_forever()

if __name__ == '__main__':
    main()
