#!/usr/bin/env python3
"""
SuperBot Agent
--------------
Maly program na PC, ktory laczy sie z SuperBotem (superbot.top1frost.pl).

Przebieg:
  1. Uruchamiasz `python superbot-agent.py`.
  2. Agent rejestruje sie na serwerze i pokazuje KOD (np. ABCD-EFGH-JKLM).
  3. Wpisujesz kod na stronie SuperBota.
  4. Asystent dostaje narzedzia do plikow/systemu na tym komputerze.

Wymagania: Python 3.8+ (tylko biblioteka standardowa).

Uzycie:
  python superbot-agent.py
  python superbot-agent.py --server https://superbot.top1frost.pl
  python superbot-agent.py --root C:\\Users\\ja\\SuperBot
  python superbot-agent.py --allow-commands      # pozwol na shell.run
  python superbot-agent.py --new-code            # nowy kod parowania
  python superbot-agent.py --reset               # zapomnij token i zacznij od nowa

Bezpieczenstwo:
  - domyslnie agent widzi tylko katalog domowy (--root zmienia, --any-path wylacza),
  - usuwanie i shell wymagaja confirm=true od modelu,
  - token jest zapisany lokalnie (chmod 600) i nie jest wysylany nigdzie poza serwer.
"""

import argparse
import json
import os
import platform
import secrets
import shutil
import socket
import stat
import subprocess
import sys
import time
import urllib.error
import urllib.parse
import urllib.request
import webbrowser

VERSION = "1.0.0"
DEFAULT_SERVER = "https://superbot.top1frost.pl"
STATE_FILE = os.path.join(os.path.expanduser("~"), ".superbot-agent.json")
MAX_READ = 200000


# --------------------------------------------------------------------------- #
# HTTP
# --------------------------------------------------------------------------- #
def _opener(insecure=False):
    handlers = []
    if insecure:
        import ssl
        ctx = ssl.create_default_context()
        ctx.check_hostname = False
        ctx.verify_mode = ssl.CERT_NONE
        handlers.append(urllib.request.HTTPSHandler(context=ctx))
    return urllib.request.build_opener(*handlers)


OPENER = _opener(False)


def request(method, url, payload=None, token=None, timeout=60):
    data = None
    headers = {"User-Agent": "SuperBot-Agent/%s" % VERSION}
    if payload is not None:
        data = json.dumps(payload).encode("utf-8")
        headers["Content-Type"] = "application/json"
    if token:
        headers["X-SuperBot-Token"] = token
    req = urllib.request.Request(url, data=data, headers=headers, method=method)
    try:
        with OPENER.open(req, timeout=timeout) as response:
            raw = response.read()
            if not raw:
                return {}
            return json.loads(raw.decode("utf-8", "replace"))
    except urllib.error.HTTPError as exc:
        body = exc.read().decode("utf-8", "replace")
        try:
            parsed = json.loads(body)
            message = parsed.get("error") or body
        except Exception:
            message = body
        raise RuntimeError("HTTP %s: %s" % (exc.code, message.strip()[:300]))
    except urllib.error.URLError as exc:
        raise RuntimeError("Nie moge polaczyc sie z serwerem: %s" % exc.reason)


# --------------------------------------------------------------------------- #
# Stan
# --------------------------------------------------------------------------- #
def load_state():
    try:
        with open(STATE_FILE, "r", encoding="utf-8") as handle:
            return json.load(handle)
    except Exception:
        return {}


def save_state(state):
    try:
        with open(STATE_FILE, "w", encoding="utf-8") as handle:
            json.dump(state, handle, indent=2)
        if os.name == "posix":
            os.chmod(STATE_FILE, stat.S_IRUSR | stat.S_IWUSR)
    except Exception as exc:
        print("[!] Nie moge zapisac %s: %s" % (STATE_FILE, exc))


# --------------------------------------------------------------------------- #
# Narzedzia
# --------------------------------------------------------------------------- #
def human_size(num):
    try:
        num = float(num)
    except Exception:
        return "?"
    for unit in ("B", "KB", "MB", "GB", "TB"):
        if num < 1024 or unit == "TB":
            return "%.1f %s" % (num, unit)
        num /= 1024.0
    return "?"


class Sandbox:
    def __init__(self, root, any_path=False):
        self.root = os.path.realpath(os.path.expanduser(root))
        self.any_path = any_path

    def resolve(self, raw):
        raw = str(raw or ".").strip()
        if not raw:
            raw = "."
        path = os.path.expanduser(raw)
        if not os.path.isabs(path):
            path = os.path.join(self.root, path)
        real = os.path.realpath(path)
        if not self.any_path:
            try:
                if os.path.commonpath([self.root, real]) != self.root:
                    raise ValueError("sciezka poza katalogiem roboczym (%s)" % self.root)
            except ValueError:
                raise ValueError("sciezka poza katalogiem roboczym (%s)" % self.root)
        return real

    def display(self, path):
        try:
            return os.path.relpath(path, self.root)
        except Exception:
            return path


def list_dir(sandbox, args):
    path = sandbox.resolve(args.get("path", "."))
    entries = []
    try:
        with os.scandir(path) as it:
            for entry in it:
                try:
                    info = entry.stat(follow_symlinks=False)
                except OSError:
                    continue
                entries.append({
                    "name": entry.name,
                    "type": "dir" if entry.is_dir(follow_symlinks=False) else "file",
                    "size": info.st_size,
                    "mtime": int(info.st_mtime),
                })
    except FileNotFoundError:
        return {"error": "nie ma takiego katalogu: %s" % sandbox.display(path)}
    entries.sort(key=lambda item: (item["type"] != "dir", item["name"].lower()))
    return {
        "path": sandbox.display(path),
        "absolute": path,
        "entries": entries[:500],
    }


def read_file(sandbox, args):
    path = sandbox.resolve(args.get("path", ""))
    if os.path.isdir(path):
        return {"error": "to jest katalog: %s" % sandbox.display(path)}
    max_bytes = max(1, min(int(args.get("max_bytes") or 20000), MAX_READ))
    with open(path, "rb") as handle:
        raw = handle.read(max_bytes + 1)
    if b"\x00" in raw[:4096]:
        return {
            "path": sandbox.display(path),
            "binary": True,
            "size": os.path.getsize(path),
            "preview_hex": raw[:64].hex(),
        }
    return {
        "path": sandbox.display(path),
        "absolute": path,
        "text": raw[:max_bytes].decode("utf-8", "replace"),
        "truncated": len(raw) > max_bytes,
        "size": os.path.getsize(path),
    }


def write_file(sandbox, args):
    path = sandbox.resolve(args.get("path", "notatka.txt"))
    content = str(args.get("content") or "")
    parent = os.path.dirname(path)
    if parent:
        os.makedirs(parent, exist_ok=True)
    mode = "a" if args.get("append") else "w"
    with open(path, mode, encoding="utf-8", newline="") as handle:
        handle.write(content)
    return {
        "ok": True,
        "path": sandbox.display(path),
        "absolute": path,
        "bytes": len(content.encode("utf-8")),
        "mode": "append" if args.get("append") else "write",
    }


def make_dir(sandbox, args):
    path = sandbox.resolve(args.get("path", "."))
    os.makedirs(path, exist_ok=True)
    return {"ok": True, "path": sandbox.display(path), "absolute": path}


def delete_path(sandbox, args):
    if not args.get("confirm"):
        return {"error": "usuwanie wymaga confirm=true"}
    path = sandbox.resolve(args.get("path", ""))
    if path == sandbox.root:
        return {"error": "odmawiam usuniecia katalogu roboczego"}
    if os.path.isdir(path) and not os.path.islink(path):
        shutil.rmtree(path)
    else:
        os.remove(path)
    return {"ok": True, "deleted": sandbox.display(path)}


def move_path(sandbox, args):
    src = sandbox.resolve(args.get("src", ""))
    dst = sandbox.resolve(args.get("dst", ""))
    parent = os.path.dirname(dst)
    if parent:
        os.makedirs(parent, exist_ok=True)
    shutil.move(src, dst)
    return {"ok": True, "src": sandbox.display(src), "dst": sandbox.display(dst)}


def system_info(sandbox, args):
    info = {
        "os": platform.system(),
        "release": platform.release(),
        "version": platform.version(),
        "machine": platform.machine(),
        "hostname": socket.gethostname(),
        "user": os.environ.get("USER") or os.environ.get("USERNAME") or "",
        "python": platform.python_version(),
        "cwd": os.getcwd(),
        "root": sandbox.root,
        "sandbox": not sandbox.any_path,
    }
    try:
        usage = shutil.disk_usage(sandbox.root)
        info["disk"] = {
            "total": usage.total,
            "used": usage.used,
            "free": usage.free,
            "total_human": human_size(usage.total),
            "free_human": human_size(usage.free),
        }
    except Exception:
        pass
    try:
        import psutil  # opcjonalnie
        info["cpu_percent"] = psutil.cpu_percent(interval=0.3)
        info["cpu_count"] = psutil.cpu_count()
        mem = psutil.virtual_memory()
        info["memory"] = {
            "total": mem.total,
            "available": mem.available,
            "percent": mem.percent,
            "total_human": human_size(mem.total),
            "available_human": human_size(mem.available),
        }
    except Exception:
        info["cpu_count"] = os.cpu_count()
    return info


def open_url(sandbox, args):
    url = str(args.get("url") or "").strip()
    if not (url.startswith("http://") or url.startswith("https://")):
        return {"error": "dozwolone sa tylko adresy http/https"}
    opened = webbrowser.open(url)
    return {"ok": True, "url": url, "opened": bool(opened)}


def run_command(sandbox, args, allow_commands):
    if not allow_commands:
        return {"error": "shell jest wylaczony. Uruchom agenta z --allow-commands."}
    if not args.get("confirm"):
        return {"error": "uruchomienie komendy wymaga confirm=true"}
    command = str(args.get("command") or "").strip()
    if not command:
        return {"error": "pusta komenda"}
    timeout = max(1, min(int(args.get("timeout") or 60), 300))
    try:
        completed = subprocess.run(
            command,
            shell=True,
            cwd=sandbox.root,
            capture_output=True,
            timeout=timeout,
            text=True,
            encoding="utf-8",
            errors="replace",
        )
    except subprocess.TimeoutExpired:
        return {"error": "komenda przekroczyla %s s" % timeout}
    return {
        "ok": completed.returncode == 0,
        "returncode": completed.returncode,
        "stdout": (completed.stdout or "")[:MAX_READ],
        "stderr": (completed.stderr or "")[:MAX_READ],
    }


def execute(task, sandbox, allow_commands):
    action = task.get("action") or ""
    args = task.get("payload") or {}
    if not isinstance(args, dict):
        args = {}
    if action == "fs.list":
        return list_dir(sandbox, args)
    if action == "fs.read":
        return read_file(sandbox, args)
    if action == "fs.write":
        return write_file(sandbox, args)
    if action == "fs.mkdir":
        return make_dir(sandbox, args)
    if action == "fs.delete":
        return delete_path(sandbox, args)
    if action == "fs.move":
        return move_path(sandbox, args)
    if action == "sys.info":
        return system_info(sandbox, args)
    if action == "browser.open":
        return open_url(sandbox, args)
    if action == "shell.run":
        return run_command(sandbox, args, allow_commands)
    return {"error": "nieznana akcja: %s" % action}


# --------------------------------------------------------------------------- #
# Parowanie
# --------------------------------------------------------------------------- #
def register(server):
    payload = {
        "name": socket.gethostname() or "PC",
        "os": platform.system(),
        "hostname": socket.gethostname(),
        "version": VERSION,
    }
    return request("POST", server + "/api/agent/register", payload)


def print_code(code, server, ttl):
    line = "=" * 54
    print()
    print(line)
    print("  KOD PAROWANIA:  %s" % code)
    print(line)
    print("  1. Otworz:  %s" % server)
    print("  2. Wpisz powyzszy kod.")
    print("  3. Kod wygasa po %d minutach." % max(1, ttl // 60))
    print()
    print("  Czekam na polaczenie...  (Ctrl+C aby przerwac)")
    print()


def pair_loop(server, state, insecure):
    token = state.get("token")
    agent_id = state.get("agent_id")
    url = "%s/api/agent/whoami?agent_id=%s" % (
        server, urllib.parse.quote(str(agent_id)))
    while True:
        try:
            data = request("GET", url, token=token, timeout=40)
        except RuntimeError as exc:
            print("[!] %s" % exc)
            time.sleep(5)
            continue
        if data.get("paired"):
            print("[+] Polaczono z SuperBotem. Asystent ma dostep do tego PC.")
            return True
        code = data.get("code")
        if code:
            print("[i] Oczekuje na kod: %s" % code)
        time.sleep(3)


def new_code(server, state):
    data = request(
        "POST",
        "%s/api/agent/new-code?agent_id=%s" % (
            server, urllib.parse.quote(str(state.get("agent_id")))),
        payload={},
        token=state.get("token"),
    )
    return data.get("code"), data.get("pair_ttl", 600)


# --------------------------------------------------------------------------- #
# Petla zadan
# --------------------------------------------------------------------------- #
def task_loop(server, state, sandbox, allow_commands, open_browser):
    token = state.get("token")
    agent_id = state.get("agent_id")
    base = "%s/api/agent" % server
    print("[i] Agent gotowy. Katalog roboczy: %s" % sandbox.root)
    if sandbox.any_path:
        print("[!] --any-path: agent widzi caly dysk.")
    if allow_commands:
        print("[!] --allow-commands: model moze uruchamiac komendy (za zgoda).")
    last_error = ""
    while True:
        try:
            data = request(
                "GET",
                "%s/poll?agent_id=%s&wait=25" % (
                    base, urllib.parse.quote(str(agent_id))),
                token=token,
                timeout=45,
            )
            last_error = ""
        except RuntimeError as exc:
            if str(exc) != last_error:
                print("[!] %s" % exc)
                last_error = str(exc)
            time.sleep(4)
            continue

        task = data.get("task")
        if not task:
            continue

        action = task.get("action")
        print("[>] %s" % action)
        try:
            result = execute(task, sandbox, allow_commands)
            ok = not (isinstance(result, dict) and result.get("error"))
        except Exception as exc:
            result = {"error": "%s: %s" % (type(exc).__name__, exc)}
            ok = False
        print("[<] %s" % ("OK" if ok else "BLAD"))

        try:
            request(
                "POST",
                "%s/result?agent_id=%s" % (
                    base, urllib.parse.quote(str(agent_id))),
                payload={
                    "task_id": task.get("id"),
                    "ok": ok,
                    "result": result,
                },
                token=token,
                timeout=30,
            )
        except RuntimeError as exc:
            print("[!] Nie wyslalem wyniku: %s" % exc)


# --------------------------------------------------------------------------- #
# Main
# --------------------------------------------------------------------------- #
def main():
    global OPENER
    parser = argparse.ArgumentParser(
        description="SuperBot Agent - daje asystentowi dostep do tego komputera.")
    parser.add_argument("--server", default=os.environ.get("SUPERBOT_SERVER", DEFAULT_SERVER))
    parser.add_argument("--root", default=os.path.expanduser("~"),
                        help="katalog roboczy agenta (domyslnie katalog domowy)")
    parser.add_argument("--any-path", action="store_true",
                        help="pozwol na sciezki poza katalogiem roboczym")
    parser.add_argument("--allow-commands", action="store_true",
                        help="pozwol modelowi uruchamiac komendy (za confirm=true)")
    parser.add_argument("--new-code", action="store_true", help="wygeneruj nowy kod parowania")
    parser.add_argument("--reset", action="store_true", help="usun zapisany token i zarejestruj od nowa")
    parser.add_argument("--no-browser", action="store_true", help="nie otwieraj przegladarki")
    parser.add_argument("--insecure", action="store_true", help="nie weryfikuj certyfikatu TLS")
    args = parser.parse_args()

    if args.insecure:
        OPENER = _opener(True)

    server = args.server.rstrip("/")
    if not (server.startswith("http://") or server.startswith("https://")):
        server = "https://" + server

    if args.reset and os.path.exists(STATE_FILE):
        os.remove(STATE_FILE)
        print("[i] Usunieto zapisany token.")

    sandbox = Sandbox(args.root, args.any_path)
    if not os.path.isdir(sandbox.root):
        os.makedirs(sandbox.root, exist_ok=True)

    state = load_state()
    if state.get("server") and state.get("server") != server:
        print("[i] Zmiana serwera (%s -> %s), rejestruje od nowa." %
              (state.get("server"), server))
        state = {}

    if not state.get("token") or not state.get("agent_id"):
        print("[i] Rejestruje agenta na %s ..." % server)
        try:
            data = register(server)
        except RuntimeError as exc:
            print("[x] %s" % exc)
            print("    Sprawdz adres: --server https://twoj-serwer")
            return 1
        state = {
            "server": server,
            "agent_id": data["agent_id"],
            "token": data["token"],
            "name": data.get("name") or socket.gethostname(),
        }
        save_state(state)
        code = data.get("code")
        ttl = data.get("pair_ttl", 600)
    else:
        state["server"] = server
        save_state(state)
        code = None
        ttl = 600

    if args.new_code or not code:
        if not code:
            try:
                code, ttl = new_code(server, state)
            except RuntimeError as exc:
                print("[!] Nie moge pobrac kodu (%s). Rejestruje od nowa." % exc)
                state = {}
                data = register(server)
                state = {
                    "server": server,
                    "agent_id": data["agent_id"],
                    "token": data["token"],
                }
                save_state(state)
                code, ttl = data.get("code"), data.get("pair_ttl", 600)

    if code:
        print_code(code, server, ttl)
        if not args.no_browser:
            try:
                webbrowser.open(server)
            except Exception:
                pass
        try:
            pair_loop(server, state, args.insecure)
        except KeyboardInterrupt:
            print("\n[i] Przerwano. Uruchom ponownie, aby dokonczyc parowanie.")
            return 0

    try:
        task_loop(server, state, sandbox, args.allow_commands, not args.no_browser)
    except KeyboardInterrupt:
        print("\n[i] Agent zatrzymany.")
    return 0


if __name__ == "__main__":
    sys.exit(main())
