import time
import requests
import subprocess
import os

WEBSITE_URL = "https://csc.jarravs.online"  # Apni Domain Name Yahan Likhein
CONFIG_FILE = "config.txt"

# SumatraPDF ka exact location path
SUMATRA_PATH = os.path.join(os.getcwd(), "SumatraPDF.exe")

def get_or_ask_api_key():
    # Agar config file pehle se hai toh usme se key read karein
    if os.path.exists(CONFIG_FILE):
        with open(CONFIG_FILE, "r") as f:
            key = f.read().strip()
            if key:
                return key

    # Agar key nahi hai toh user se pucho
    print("\n==========================================")
    print("      CSC AUTO PRINT AGENT SETUP          ")
    print("==========================================")
    user_key = input("Kripya apni Shop API Key enter karein: ").strip()

    if user_key:
        with open(CONFIG_FILE, "w") as f:
            f.write(user_key)
        print("[+] Shop Key Successfully Saved!\n")
        return user_key
    else:
        print("[!] Invalid Key. Application band ho rahi hai.")
        time.sleep(3)
        exit()

def poll_and_print(shop_api_key):
    try:
        url = f"{WEBSITE_URL}/api/get_pending_jobs.php?shop_key={shop_api_key}"
        res = requests.get(url, timeout=5).json()

        if res.get('success') and res.get('has_job'):
            job = res['job']
            print(f"[*] Naya Print Order Aaya: {job['order_id']}")

            # PDF Download karein
            pdf_res = requests.get(job['file_url'])
            temp_file = "temp_print.pdf"
            with open(temp_file, "wb") as f:
                f.write(pdf_res.content)

            # Print Settings Setup
            settings = []
            if job['page_selection'] in ['odd', 'even']:
                settings.append(job['page_selection'])
            elif job['page_selection'] == 'custom' and job['custom_pages']:
                settings.append(job['custom_pages'])

            if job['copies'] > 1:
                settings.append(f"{job['copies']}x")

            settings_str = ",".join(settings)
            
            # SumatraPDF Command Execute
            if settings_str:
                cmd = f'"{SUMATRA_PATH}" -print-to-default -print-settings "{settings_str}" "{temp_file}"'
            else:
                cmd = f'"{SUMATRA_PATH}" -print-to-default "{temp_file}"'

            subprocess.run(cmd, shell=True)

            # Status Update Karein
            requests.post(f"{WEBSITE_URL}/api/update_job_status.php", data={
                'job_id': job['id'],
                'status': 'PRINTED',
                'shop_key': shop_api_key
            })
            print(f"[+] Order {job['order_id']} Successfully Print Ho Gaya!\n")

    except Exception as e:
        pass # Silent error backgrounding

if __name__ == "__main__":
    api_key = get_or_ask_api_key()
    print(f"=== AUTO PRINT AGENT RUNNING (Shop Key: {api_key}) ===")
    print("Is Window ko minime kar dein, band mat karein.\n")
    
    while True:
        poll_and_print(api_key)
        time.sleep(3)