import os
import sys
import argparse
import json
import urllib.request
import sqlite3

class QzoticLiveExecutionEngine:
    def __init__(self, token_file_path, db_path="/Users/bpa/ForesixaQuant/trading_live.db"):
        self.token_file_path = token_file_path
        self.db_path = db_path
        self.api_key_id = None
        self.api_secret_key = None
        
        # Initialize an isolated production ledger tracking data rows cleanly
        conn = sqlite3.connect(self.db_path)
        cursor = conn.cursor()
        cursor.execute("PRAGMA foreign_keys = ON;")
        cursor.execute("""
            CREATE TABLE IF NOT EXISTS production_trades_ledger (
                trade_id TEXT PRIMARY KEY,
                symbol TEXT NOT NULL,
                execution_qty TEXT NOT NULL,
                execution_price_cents INTEGER NOT NULL,
                timezone_aware_timestamp TEXT NOT NULL,
                risk_allocation_ratio TEXT NOT NULL
            );
        """)
        conn.commit()
        conn.close()

        # Ingest private credentials natively from your secure hidden vault path
        print(f"[INIT] Extracting keys from path target: {self.token_file_path}")
        if not os.path.exists(self.token_file_path):
            print(f" -> [CRITICAL AUTH ERROR] Token target file not found on disk: {self.token_file_path}")
            sys.exit(1)
        try:
            with open(self.token_file_path, "r", encoding="utf-8") as f:
                raw_token_data = f.read().strip()
            credentials = json.loads(raw_token_data)
            self.api_key_id = credentials.get("api_key_id")
            self.api_secret_key = credentials.get("api_secret_key")
            if not self.api_key_id or not self.api_secret_key:
                raise KeyError("Missing required sub-keys inside private token JSON.")
            print(" -> [SUCCESS] Secure cryptographic credentials loaded cleanly into memory.")
        except Exception as e:
            print(f" -> [AUTH ABORTED] Failed parsing local private token metadata: {str(e)}")
            sys.exit(1)

    def verify_alpaca_handshake(self):
        # STCKING ACCURATELY TO YOUR SECURE LIVE ACCOUNT RAILS
        endpoint_url = "https://alpaca.markets"
        print(f"\n[LIVE API SHAKEDOWN] Attempting secure gateway handshake to: {endpoint_url}")
        
        req = urllib.request.Request(endpoint_url)
        req.add_header("APCA-API-KEY-ID", self.api_key_id)
        req.add_header("APCA-API-SECRET-KEY", self.api_secret_key)
        try:
            with urllib.request.urlopen(req, timeout=10.0) as response:
                response_data = json.loads(response.read().decode("utf-8"))
                account_id = response_data.get("id")
                trading_blocked = response_data.get("trading_blocked", True)
                print("============================================================")
                print("     ALPACA LIVE API STATUS: CONNECTED & VERIFIED           ")
                print("============================================================")
                print(f"   • Live Account Identifier Token : {account_id}")
                print(f"   • Real-Money Trading Capability : {'BLOCKED_SUSPENDED' if trading_blocked else 'ACTIVE - LIVE'}")
                print("============================================================\n")
                return True
        except urllib.error.HTTPError as http_err:
            print(f"   - [HANDSHAKE REJECTED] Alpaca live server returned network error code: {http_err.code}")
            if http_err.code == 401:
                print("     Reason: The keys inside your token file belong to your paper dashboard, or your live keys have rotated.")
            return False
        except Exception as conn_err:
            print(f"   - [NETWORK BLOCK] Connection failed: {str(conn_err)}")
            return False

if __name__ == "__main__":
    parser = argparse.ArgumentParser(description="Standalone Qzotic Live Production Engine")
    parser.add_argument("--token-file", required=True, help="Absolute path to private token file")
    args = parser.parse_args()
    bot = QzoticLiveExecutionEngine(token_file_path=args.token_file)
    bot.verify_alpaca_handshake()
