"""
apiPrinter.py v5.0 - Aurora POS
Sin dependencias de pywin32 - usa subprocess + comandos nativos de Windows
Corre HTTP en puerto 5000 + HTTPS en puerto 5001
"""
import os, sys, json, time, tempfile, logging, threading, subprocess
import requests as req_lib
from flask import Flask, request, jsonify
from urllib.parse import unquote

app = Flask(__name__)
logging.getLogger('werkzeug').setLevel(logging.ERROR)

# ── Auto-registro inicio Windows (via REG) ────────────────────────────────────
def get_exe_path():
    return sys.executable if getattr(sys, 'frozen', False) else os.path.abspath(__file__)

def register_startup():
    try:
        exe = get_exe_path()
        subprocess.run([
            'reg', 'add',
            r'HKCU\Software\Microsoft\Windows\CurrentVersion\Run',
            '/v', 'AuroraPOS_Printer',
            '/t', 'REG_SZ',
            '/d', f'"{exe}"',
            '/f'
        ], capture_output=True, timeout=5)
    except Exception:
        pass

def is_registered():
    try:
        result = subprocess.run([
            'reg', 'query',
            r'HKCU\Software\Microsoft\Windows\CurrentVersion\Run',
            '/v', 'AuroraPOS_Printer'
        ], capture_output=True, timeout=5)
        return result.returncode == 0
    except Exception:
        return False

# ── CORS ──────────────────────────────────────────────────────────────────────
@app.after_request
def add_cors(r):
    r.headers['Access-Control-Allow-Origin']  = '*'
    r.headers['Access-Control-Allow-Headers'] = 'Content-Type,Authorization'
    r.headers['Access-Control-Allow-Methods'] = 'GET,POST,OPTIONS'
    return r

# ── Listar impresoras (via WMIC) ──────────────────────────────────────────────
def get_printers_list():
    try:
        result = subprocess.run(
            ['wmic', 'printer', 'get', 'Name'],
            capture_output=True, text=True, timeout=10
        )
        lines = result.stdout.strip().split('\n')
        printers = [l.strip() for l in lines[1:] if l.strip()]
        return printers
    except Exception:
        return []

# ── Imprimir silenciosamente (via PowerShell) ─────────────────────────────────
def print_silent(filepath, printer):
    cmd = (
        f'$job = Start-Job {{ '
        f'  $sh = New-Object -ComObject Shell.Application; '
        f'  $sh.ShellExecute("{filepath}", "", "", "print", 0) '
        f'}}; '
        f'Wait-Job $job -Timeout 30 | Out-Null'
    )
    try:
        subprocess.Popen(
            ['powershell', '-NonInteractive', '-WindowStyle', 'Hidden',
             '-Command', cmd],
            stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL
        )
        time.sleep(3)
    except Exception:
        # Fallback: rundll32 printui
        try:
            subprocess.Popen(
                ['rundll32', 'printui.dll,PrintUIEntry',
                 '/q', '/p', f'/n{printer}', f'/f{filepath}'],
                stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL
            )
            time.sleep(3)
        except Exception:
            pass

# ── HTML de popup ─────────────────────────────────────────────────────────────
def popup_html(title, icon, message, post_js):
    return f"""<!DOCTYPE html>
<html><head><meta charset="utf-8"><title>{title}</title>
<style>body{{font-family:Arial,sans-serif;background:#f0f4f8;display:flex;
align-items:center;justify-content:center;height:100vh;margin:0;}}
.box{{background:#fff;padding:24px 32px;border-radius:10px;
box-shadow:0 4px 20px rgba(0,0,0,.15);text-align:center;max-width:340px;}}
.icon{{font-size:40px;margin-bottom:10px;}}
h3{{margin:0 0 6px;font-size:16px;}}
p{{color:#666;font-size:13px;margin:4px 0;}}</style></head>
<body><div class="box">
<div class="icon">{icon}</div>
<h3>{title}</h3><p>{message}</p>
<p style="font-size:11px;color:#aaa;margin-top:14px;">Esta ventana se cierra sola...</p>
</div>
<script>
try{{if(window.opener&&!window.opener.closed){{window.opener.postMessage({post_js},'*');}}}}catch(e){{}}
setTimeout(function(){{window.close();}},1800);
</script></body></html>"""

# ── Endpoints JSON ────────────────────────────────────────────────────────────
@app.route('/status', methods=['GET','OPTIONS'])
def status():
    if request.method == 'OPTIONS': return jsonify({}), 200
    return jsonify({"status": "running", "version": "5.0"})

@app.route('/printers', methods=['GET','OPTIONS'])
def printers():
    if request.method == 'OPTIONS': return jsonify({}), 200
    return jsonify({"printers": get_printers_list()})

@app.route('/print/<printer_name>/<path:pdf_url>', methods=['GET','OPTIONS'])
def print_get(printer_name, pdf_url):
    if request.method == 'OPTIONS': return jsonify({}), 200
    try:
        r = req_lib.get(unquote(pdf_url), timeout=15); r.raise_for_status()
        tmp = tempfile.NamedTemporaryFile(delete=False, suffix='.pdf')
        tmp.write(r.content); tmp.close()
        print_silent(tmp.name, unquote(printer_name))
        try: time.sleep(2); os.remove(tmp.name)
        except: pass
        return jsonify({"message": "ok"})
    except Exception as e:
        return jsonify({"error": str(e)}), 500

@app.route('/print', methods=['POST','OPTIONS'])
def print_post():
    if request.method == 'OPTIONS': return jsonify({}), 200
    data = request.get_json() or {}
    try:
        r = req_lib.get(data['url'], timeout=15); r.raise_for_status()
        tmp = tempfile.NamedTemporaryFile(delete=False, suffix='.pdf')
        tmp.write(r.content); tmp.close()
        print_silent(tmp.name, data['printer'])
        try: time.sleep(2); os.remove(tmp.name)
        except: pass
        return jsonify({"message": "ok"})
    except Exception as e:
        return jsonify({"error": str(e)}), 500

# ── Endpoints Popup (postMessage, para HTTPS) ─────────────────────────────────
@app.route('/launch', methods=['GET'])
def launch():
    pl = get_printers_list()
    return popup_html(
        "Aurora POS — Servicio activo", "🖨️",
        f"Impresoras detectadas: <strong>{len(pl)}</strong>",
        json.dumps({"type": "PRINTER_LIST", "printers": pl})
    )

@app.route('/trigger-print', methods=['GET'])
def trigger_print():
    printer = request.args.get('printer', '')
    url     = request.args.get('url', '')
    try:
        r = req_lib.get(url, timeout=15); r.raise_for_status()
        tmp = tempfile.NamedTemporaryFile(delete=False, suffix='.pdf')
        tmp.write(r.content); tmp.close()
        print_silent(tmp.name, printer)
        try: time.sleep(2); os.remove(tmp.name)
        except: pass
        return popup_html("Imprimiendo", "✅", "Ticket enviado correctamente",
                          json.dumps({"type":"PRINT_RESULT","success":True,"msg":"ok"}))
    except Exception as e:
        return popup_html("Error", "❌", str(e),
                          json.dumps({"type":"PRINT_RESULT","success":False,"msg":str(e)}))

# ── Servidores HTTP + HTTPS ───────────────────────────────────────────────────
def run_https():
    try:
        app.run(host='0.0.0.0', port=5001, debug=False,
                use_reloader=False, ssl_context='adhoc')
    except Exception:
        pass  # pyOpenSSL no disponible, solo HTTP

if __name__ == '__main__':
    if not is_registered():
        register_startup()

    t = threading.Thread(target=run_https, daemon=True)
    t.start()
    app.run(host='0.0.0.0', port=5000, debug=False, use_reloader=False, threaded=True)
