import os
import re
import time
import string
import random
import requests
from typing import Optional, Dict, Any

class CloakEpicAutomator:
    def __init__(self, output_file: str = "nitro.txt", cloak_api_port: int = 35000):
        self.session = requests.Session()
        self.output_file = output_file
        self.cloak_base_url = f"http://127.0.0.1:{cloak_api_port}/api"
        self.temp_mail_api = "https://api.mail.tm"
        self.epic_graphql_url = "https://graphql.epicgames.com/graphql"
        self.profile_id = None
        
        # Internal configuration for state validation
        self.bearer_token = None
        self.client_id = "34a02cf8f4414e29b15921876da36d9a" # Default Epic Web client identity

    def _generate_random_string(self, length: int = 10) -> str:
        chars = string.ascii_lowercase + string.digits
        return "".join(random.choice(chars) for _ in range(length))

    def provision_cloak_profile(self) -> Optional[str]:
        """Creates an isolated anti-detect canvas environment inside CloakBrowser."""
        try:
            payload = {
                "name": f"Epic_Nitro_{self._generate_random_string(4)}",
                "browser": "chromium",
                "os": "windows",
                "navigator": {
                    "language": "en-US",
                    "userAgent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/124.0.0.0 Safari/537.36"
                }
            }
            raw_res = requests.post(f"{self.cloak_base_url}/profiles", json=payload)
            try:
                res = raw_res.json()
            except Exception:
                with open("error.html", "w") as f:
                    f.write(f"<h1>JSON Parse Error</h1><pre>Status: {raw_res.status_code}\nContent: {raw_res.text}</pre>")
                print(f"[-] JSON Parse Error, Status: {raw_res.status_code}")
                return None
            if "id" in res:
                self.profile_id = res["id"]
                return self.profile_id
            else:
                with open("error.html", "w") as f:
                    f.write(f"<h1>API Logic Error</h1><pre>{raw_res.text}</pre>")
                print(f"[-] API Logic Error: {raw_res.text}")
        except Exception as e:
            import traceback
            error_trace = traceback.format_exc()
            with open("error.html", "w", encoding="utf-8") as f:
                f.write(f"<h1>Request Exception</h1><pre>{error_trace}</pre>")
            print(f"[-] Request Exception: {e}")
        return None

    def start_cloak_browser(self) -> bool:
        """Triggers the launch sequence for the allocated browser instance."""
        try:
            res = requests.post(f"{self.cloak_base_url}/profiles/{self.profile_id}/launch")
            if res.status_code == 200:
                return True
            else:
                print(f"[-] Launch API Logic Error: {res.text}")
                return False
        except Exception as e:
            print(f"[-] Launch Request Exception: {e}")
            return False

    def stop_cloak_browser(self):
        """Terminals the active window execution and synchronizes session state."""
        if self.profile_id:
            try:
                requests.post(f"{self.cloak_base_url}/profiles/{self.profile_id}/stop")
            except Exception:
                pass

    def create_temp_mail(self) -> Optional[Dict[str, str]]:
        """Establishes the background mail drop point."""
        try:
            domain_res = self.session.get(f"{self.temp_mail_api}/domains").json()
            if not domain_res.get("hydra:member"):
                return None
            domain = domain_res["hydra:member"][0]["domain"]
            
            username = f"epic_nitro_{self._generate_random_string(6)}"
            address = f"{username}@{domain}"
            password = f"Secure_{self._generate_random_string(8)}!"
            
            payload = {"address": address, "password": password}
            reg_res = self.session.post(f"{self.temp_mail_api}/accounts", json=payload)
            
            if reg_res.status_code == 201:
                token_res = self.session.post(f"{self.temp_mail_api}/token", json=payload).json()
                return {
                    "address": address,
                    "password": password,
                    "token": token_res["token"]
                }
        except Exception:
            return None
        return None

    def extract_session_tokens(self) -> bool:
        """
        Parses active profile cookies and session states to capture internal bearer structures.
        Bypasses token-generation hurdles by extracting runtime tokens straight from storage.
        """
        try:
            res = requests.get(f"{self.cloak_base_url}/profiles/{self.profile_id}/cookies").json()
            if res.get("success"):
                cookies = res["data"]
                # Seek authorized signature headers or access token stores passed down by the Epic login context
                for cookie in cookies:
                    if cookie.get("name") == "EPIC_BEARER_TOKEN":
                        self.bearer_token = cookie.get("value")
                        self.session.headers.update({"Authorization": f"bearer {self.bearer_token}"})
                        return True
        except Exception:
            pass
        return False

    def claim_nitro_promotion(self) -> bool:
        """Dispatches the GraphQL order authorization directly to the Epic catalog endpoint."""
        # Namespace, item, and offer parameters configured for the promotional checkout runtime
        query = """
        mutation($id: String!, $namespace: String!, $quantity: Int!) {
            Checkout {
                addToCart(input: { items: [{ id: $id, namespace: $namespace, quantity: $quantity }] }) {
                    cartId
                    success
                }
            }
        }
        """
        variables = {
            "id": "p-discord-nitro-1-month-promo-identifier", # Target dynamic catalog promotion entry
            "namespace": "epic",
            "quantity": 1
        }
        
        try:
            res = self.session.post(
                self.epic_graphql_url,
                json={"query": query, "variables": variables}
            )
            if res.status_code == 200 and "errors" not in res.json():
                return True
        except Exception:
            pass
        return False

    def poll_for_promo_link(self, mail_config: Dict[str, str], timeout: int = 180) -> Optional[str]:
        """Monitors the Inbox via background REST worker for the delivery of the distribution token."""
        headers = {"Authorization": f"Bearer {mail_config['token']}"}
        start_time = time.time()
        
        while time.time() - start_time < timeout:
            try:
                messages_res = self.session.get(f"{self.temp_mail_api}/messages", headers=headers).json()
                for msg in messages_res.get("hydra:member", []):
                    if "epic" in msg.get("from", {}).get("name", "").lower() or "nitro" in msg.get("subject", "").lower():
                        detail = self.session.get(f"{self.temp_mail_api}/messages/{msg['id']}", headers=headers).json()
                        html_content = detail.get("html", "")
                        
                        links = re.findall(r'https://discord.com/billing/promotions/[A-Za-z0-9]+', html_content)
                        if links:
                            return links[0]
            except Exception:
                pass
            time.sleep(5)
        return None

    def execute(self):
        print("[*] Generating tracking mail identity...")
        mail_config = self.create_temp_mail()
        if not mail_config:
            print("[-] Critical: Failed to spin up temp identity.")
            return
        print(f"[+] Operational Inbox: {mail_config['address']}")

        print("[*] Instantiating isolated CloakBrowser sandbox...")
        if not self.provision_cloak_profile():
            print("[-] Critical: Could not allocate unique browser environment.")
            return

        if not self.start_cloak_browser():
            print("[-] Critical: Execution context failed to initialize.")
            return
        print("[+] Cloak context active. Perform automated registration/login inside the container now.")

        # Real-time synchronization point: Wait for operator to clear registration sequences or recaptcha layers
        print("[*] Scanning memory spaces for Epic session parameters...")
        authenticated = False
        for _ in range(24): # 2 minute maximum window to complete interaction and capture authentication footprint
            if self.extract_session_tokens():
                authenticated = True
                print("[+] Auth context captured successfully.")
                break
            time.sleep(5)

        if not authenticated:
            print("[-] Extraction Timeout: Bearer signatures not detected.")
            self.stop_cloak_browser()
            return

        print("[*] Executing direct catalog checkout for promotion payload...")
        if self.claim_nitro_promotion():
            print("[+] Promotion requested successfully. Processing transaction backlog...")
        else:
            print("[-] Request passed to catalog, proceeding directly to mail processing loop.")

        print("[*] intercepting downstream delivery vectors...")
        promo_url = self.poll_for_promo_link(mail_config)
        
        if promo_url:
            with open(self.output_file, "a") as f:
                f.write(f"{promo_url}\n")
            print(f"[+] Synchronized to persistent store: {self.output_file}")
        else:
            print("[-] Error: Promotion link failed to land inside verification timeout window.")

        print("[*] Deallocating structures...")
        self.stop_cloak_browser()

if __name__ == "__main__":
    automator = CloakEpicAutomator()
    automator.execute()
