#!/usr/bin/env python3
"""Portable Listener v2.6 - SSL Fixed"""
import sys
sys.path.insert(0, '../python/Lib/site-packages')

import requests
import subprocess
import time
import os
from datetime import datetime

# Disable SSL warnings for portable Python
import urllib3
urllib3.disable_warnings(urllib3.exceptions.InsecureRequestWarning)

# Config
try:
    from config import *
except:
    API_URL = "https://wintask.92-5-72-169.sslip.io"
    TELEGRAM_BOT = ""
    TELEGRAM_CHAT = ""
    CHECK_INTERVAL = 10

LOG_FILE = "listener.log"

def log(msg):
    ts = datetime.now().strftime("%Y-%m-%d %H:%M:%S")
    line = f"[{ts}] {msg}"
    print(line)
    try:
        with open(LOG_FILE, "a", encoding="utf-8") as f:
            f.write(line + "\n")
    except: pass

def telegram(text):
    if TELEGRAM_BOT and TELEGRAM_CHAT:
        try:
            requests.post(f"https://api.telegram.org/bot{TELEGRAM_BOT}/sendMessage",
                          json={"chat_id": TELEGRAM_CHAT, "text": text[:4000]}, 
                          timeout=10, verify=False)
        except: pass

def get_task():
    try:
        r = requests.get(f"{API_URL}/task", timeout=15, verify=False)
        task = r.json().get("task")
        if task and task.get("status") == "pending":
            return task
    except Exception as e:
        log(f"Error getting task: {e}")
    return None

def send_result(result, task_id=""):
    try:
        requests.post(f"{API_URL}/result", 
                     json={"result": result, "task_id": task_id}, 
                     timeout=15, verify=False)
    except Exception as e:
        log(f"Error sending result: {e}")

def execute_powershell(cmd):
    try:
        r = subprocess.run(["powershell", "-Command", cmd],
                          capture_output=True, text=True, timeout=60)
        return (r.stdout + r.stderr)[:4000]
    except Exception as e:
        return f"PS Error: {e}"

def execute_python(code):
    try:
        r = subprocess.run(["python", "-c", code],
                          capture_output=True, text=True, timeout=60)
        return (r.stdout + r.stderr)[:4000]
    except Exception as e:
        return f"PY Error: {e}"

def execute_claude(prompt, timeout=120):
    try:
        r = subprocess.run(
            f'claude -p --dangerously-skip-permissions "{prompt}"',
            capture_output=True, text=True, timeout=timeout, shell=True
        )
        return (r.stdout + r.stderr)[:4000]
    except subprocess.TimeoutExpired:
        return f"Claude timeout after {timeout}s"
    except Exception as e:
        return f"Claude error: {e}"

def execute(task_text):
    upper = task_text.upper().strip()
    
    if upper == "PING":
        return f"PONG! Listener v2.6 active - {datetime.now()}"
    
    if upper == "STATUS":
        import platform
        return f"Portable Listener v2.6\nOS: {platform.system()} {platform.release()}\nPython: {platform.python_version()}\nHost: {platform.node()}\nPID: {os.getpid()}"
    
    if upper in ["STOP", "EXIT", "QUIT"]:
        log("Stop command received")
        telegram("Listener stopped by command")
        return "STOPPING"
    
    if upper == "RESTART":
        log("Restart command")
        os.system("start cmd /c START_LISTENER.bat")
        return "RESTARTING"
    
    # PowerShell
    if task_text.upper().startswith("PS:"):
        cmd = task_text[3:].strip()
        log(f"PowerShell: {cmd[:50]}")
        return execute_powershell(cmd)
    
    # Python
    if task_text.upper().startswith("PY:"):
        code = task_text[3:].strip()
        log(f"Python: {code[:50]}")
        return execute_python(code)
    
    # CMD
    if task_text.upper().startswith("CMD:"):
        cmd = task_text[4:].strip()
        log(f"CMD: {cmd[:50]}")
        try:
            r = subprocess.run(cmd, capture_output=True, text=True, timeout=60, shell=True)
            return (r.stdout + r.stderr)[:4000]
        except Exception as e:
            return f"CMD Error: {e}"
    
    # Default: Claude Code
    log(f"Claude: {task_text[:50]}")
    return execute_claude(task_text)

def main():
    log("=" * 50)
    log("PORTABLE LISTENER v2.6 STARTED (SSL Fixed)")
    log(f"API: {API_URL}")
    log("=" * 50)
    
    telegram("Listener v2.6 started")
    errors = 0
    
    while True:
        try:
            task = get_task()
            if task:
                task_id = task.get("id", "")
                task_text = task.get("message", "")
                
                log(f"Task {task_id}: {task_text[:50]}...")
                
                result = execute(task_text)
                send_result(result, task_id)
                
                log(f"Done: {result[:100]}...")
                
                if result == "STOPPING":
                    break
            
            errors = 0
            
        except KeyboardInterrupt:
            log("Interrupted by user")
            break
        except Exception as e:
            errors += 1
            log(f"Error ({errors}): {e}")
            if errors >= 10:
                log("Too many errors, waiting 60s...")
                time.sleep(60)
                errors = 0
        
        time.sleep(CHECK_INTERVAL)
    
    log("Listener stopped")
    telegram("Listener stopped")

if __name__ == "__main__":
    main()
