"""Edgemode Device Bridge - lets Edgemode Code Studio (web) work on a project folder on THIS PC and run
commands in it (a real terminal), always after you approve in the web app.

    py edgemode_bridge.py                           # asks which project folder to share (or double-click the file)
    python edgemode_bridge.py --folder "C:\\code\\myapp"
    python edgemode_bridge.py --allow-origin https://studio.example.com   # extra web app address (exact)
    python edgemode_bridge.py --forget-pairings

Safety (on top of the approvals in the web app):
  * listens only on 127.0.0.1 (other computers can't reach it)
  * answers only the exact Code Studio web addresses in bridge_config.json (no wildcards; by default
    https://code-studio.edgemode.ai and a Code Studio on this PC at port 7864), and only after pairing
    with the 6-digit code shown in this window
  * pairing: a code is good for 10 minutes and 5 tries (then a new one is shown), wrong codes are
    answered slowly, and after 10 wrong codes pairing is off until the bridge is restarted
  * a pairing works only for the web address that made it
  * everything stays inside the shared project folder (no "..", no other drives, no credential folders)
  * dangerous commands (format, registry edits, shutdown, deleting from the shell, download-and-run, ...)
    are refused; deletes made by the agent go to .edgemode-trash inside the project
  * every operation is printed in this window. Close the window to cut the connection.

Standard library only: no packages to install.
"""
from __future__ import annotations

import argparse
import base64
import fnmatch
import hashlib
import json
import os
import platform
import re
import secrets
import shutil
import subprocess
import sys
import threading
import time
from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer
from pathlib import Path
from urllib.parse import urlparse

VERSION = "1.1.0"
CONF_DIR = Path.home() / ".edgemode-bridge"
CONF = CONF_DIR / "bridge_config.json"
DEFAULT_ORIGINS = ["https://code-studio.edgemode.ai", "http://127.0.0.1:7864", "http://localhost:7864"]
# 1.0.0 defaults: wildcards that also matched every other edgemode.ai site (including pages that
# customers control) and any web server on this PC. Removed from saved settings on start.
OLD_DEFAULT_ORIGINS = {"https://edgemode.ai", "https://*.edgemode.ai", "http://127.0.0.1:*", "http://localhost:*"}
CODE_TTL = 600            # seconds a pairing code is good for
CODE_TRIES = 5            # wrong codes before a new code is shown
MAX_PAIR_FAILS = 10       # wrong codes before pairing is off until restart
MAX_READ = 20 * 1024 * 1024
SKIP_DIRS = {".git", "node_modules", "__pycache__", ".venv", "venv", ".edgemode-trash", "$RECYCLE.BIN"}
IS_WIN = os.name == "nt"
HOME = Path.home()
PROTECTED = [HOME / ".ssh", HOME / ".gnupg", HOME / ".aws", HOME / ".azure", HOME / ".kube", HOME / ".docker",
             HOME / ".edgemode-bridge", HOME / "AppData" / "Roaming" / "Microsoft" / "Credentials",
             HOME / "AppData" / "Roaming" / "Microsoft" / "Protect", HOME / "AppData" / "Local" / "Google" / "Chrome" / "User Data",
             HOME / "AppData" / "Local" / "Microsoft" / "Edge" / "User Data", HOME / "AppData" / "Roaming" / "Mozilla" / "Firefox",
             Path(os.environ.get("SystemRoot", r"C:\Windows"))]
BLOCKED = [
    (r"\bformat(\.com)?\s+[a-z]:", "formatting drives"), (r"\bdiskpart\b", "disk partitioning"),
    (r"\b(bcdedit|bootrec)\b", "boot configuration"), (r"\b(vssadmin|wbadmin)\b", "shadow copies/backups"),
    (r"\bcipher\s+/w", "wiping free space"), (r"\b(shutdown|restart-computer|stop-computer)\b", "shutting down"),
    (r"\breg(\.exe)?\s+(delete|add|import)\b|\b(remove|set|new)-itemproperty\b.*hk(lm|cu)", "registry edits"),
    (r"set-executionpolicy", "changing script policy"), (r"(^|[\s;|&(])(iex|invoke-expression)\b", "executing dynamic code"),
    (r"(curl|wget|iwr|irm|invoke-webrequest|invoke-restmethod)\b[^\n]*\|\s*(iex|sh|bash|cmd|powershell|pwsh|python|py)\b",
     "piping downloads into a shell"),
    (r"\bnet\s+(user|localgroup)\b|\b(new|remove|set)-localuser\b", "user account changes"),
    (r"\b(takeown|icacls|cacls)\b", "changing file permissions"),
    (r"\bschtasks\b.*/(create|change)|\bregister-scheduledtask\b", "creating scheduled tasks"),
    (r"\bsc(\.exe)?\s+(create|delete|config)\b|\b(new|remove)-service\b", "service changes"),
    (r"-enc(odedcommand)?\s", "encoded commands"), (r"set-mppreference|add-mppreference|disable.?defender", "disabling Defender"),
    (r"\b(wevtutil\s+cl|clear-eventlog)\b", "clearing event logs"), (r"\bmimikatz|sekurlsa|lsass\b", "credential dumping"),
    (r"(^|[;&|(]\s*)(rm|del|erase|rd|rmdir|remove-item|ri)\s|/c\s+(del|erase|rd|rmdir)\s", "deleting from the shell"),
    (r"\b(format-volume|clear-disk|initialize-disk|remove-partition)\b", "disk changes"),
    (r"\bgit\s+(push\s+.*--force|push\s+-f|reset\s+--hard|clean\s+-[a-z]*f)", "destructive git operations"),
    (r"\.ssh|login data|\\credentials\\", "credential locations"),
]


def now():
    return time.strftime("%H:%M:%S")


def log(msg):
    print(f"[{now()}] {msg}", flush=True)


def is_under(child: Path, parent: Path) -> bool:
    c, p = os.path.normcase(str(child)), os.path.normcase(str(parent))
    try:
        return os.path.commonpath([c, p]) == p
    except ValueError:
        return False


class BridgeError(Exception):
    pass


def norm_origin(o: str) -> str | None:
    """'https://host[:port]' exactly (what a browser sends as Origin), or None. http only for this PC."""
    o = str(o or "").strip().rstrip("/").lower()
    u = urlparse(o)
    if not re.fullmatch(r"https?://[a-z0-9.\-]+(:\d{1,5})?", o) or not u.hostname:
        return None
    if u.scheme == "http" and u.hostname not in ("127.0.0.1", "localhost"):
        return None
    return o


# ====================================================================== settings / pairing
class Config:
    def __init__(self):
        self.data = {"origins": list(DEFAULT_ORIGINS), "tokens": {}, "folder": ""}
        try:
            self.data.update(json.loads(CONF.read_text(encoding="utf-8")))
        except (OSError, ValueError):
            pass
        kept = [n for n in (norm_origin(o) for o in self.data.get("origins") or [] if o not in OLD_DEFAULT_ORIGINS) if n]
        self.data["origins"] = list(dict.fromkeys(DEFAULT_ORIGINS + kept))
        self.lock = threading.Lock()

    def save(self):
        CONF_DIR.mkdir(parents=True, exist_ok=True)
        try:
            os.chmod(CONF_DIR, 0o700)
        except OSError:
            pass
        with self.lock:
            CONF.write_text(json.dumps(self.data, indent=2), encoding="utf-8")
        try:
            os.chmod(CONF, 0o600)
        except OSError:
            pass

    def origin_ok(self, origin: str) -> bool:
        o = norm_origin(origin)
        return bool(o) and o in self.data["origins"]

    def token_ok(self, token: str, origin: str) -> bool:
        """A pairing is good only from the (still allowed) web address that made it."""
        if not token or not self.origin_ok(origin):
            return False
        t = self.data["tokens"].get(hashlib.sha256(token.encode()).hexdigest())
        return bool(t) and norm_origin(t.get("origin")) == norm_origin(origin)

    def add_token(self, origin: str, name: str) -> str:
        token = secrets.token_urlsafe(32)
        self.data["tokens"][hashlib.sha256(token.encode()).hexdigest()] = {
            "origin": origin, "name": name[:80], "created": time.strftime("%Y-%m-%d %H:%M")}
        self.save()
        return token


# ====================================================================== project folder operations
class Project:
    def __init__(self, root: Path):
        self.root = root.resolve()
        self.trash = self.root / ".edgemode-trash"

    def path(self, rel: str, must_exist=False) -> Path:
        raw = str(rel or ".").replace("\\", "/")
        if re.match(r"^[a-zA-Z]:", raw) or raw.startswith("/") or raw.startswith("~") or "\x00" in raw:
            raise BridgeError("Only paths inside the project folder are allowed.")
        if any(part == ".." for part in raw.split("/")):
            raise BridgeError("Paths may not go above the project folder.")
        p = (self.root / raw).resolve()       # also resolves links, so they can't lead outside
        if not is_under(p, self.root):
            raise BridgeError("That path leads outside the project folder.")
        if any(is_under(p, d) for d in PROTECTED):
            raise BridgeError("That is a protected location.")
        if must_exist and not p.exists():
            raise BridgeError(f"Not found: {rel}")
        return p

    def rel(self, p: Path) -> str:
        return p.relative_to(self.root).as_posix()

    # ---- ops ----
    def op_list(self, a):
        base = self.path(a.get("path"), True)
        if not base.is_dir():
            raise BridgeError("Not a folder")
        out, limit, trunc = [], int(a.get("max") or 300), False
        it = self._walk(base) if a.get("recursive") else sorted(base.iterdir(), key=lambda x: x.name.lower())
        for p in it:
            if len(out) >= limit:
                trunc = True
                break
            if p.name == ".edgemode-trash" and p.parent == self.root:
                continue
            try:
                st = p.stat()
                out.append({"path": self.rel(p), "dir": p.is_dir(), "size": st.st_size, "mtime": int(st.st_mtime * 1000)})
            except OSError:
                continue
        return {"entries": out, "truncated": trunc}

    def _walk(self, base):
        for dirpath, dirnames, filenames in os.walk(base):
            dirnames[:] = sorted(d for d in dirnames if d not in SKIP_DIRS)
            d = Path(dirpath)
            for n in dirnames:
                yield d / n
            for n in sorted(filenames):
                yield d / n

    def op_read(self, a):
        p = self.path(a.get("path"))
        if not p.exists():
            return {"exists": False}
        if not p.is_file():
            raise BridgeError("Not a file (it is a folder)")
        if p.stat().st_size > MAX_READ:
            raise BridgeError("The file is larger than 20 MB.")
        return {"exists": True, "data": base64.b64encode(p.read_bytes()).decode(), "size": p.stat().st_size}

    def op_write(self, a):
        p = self.path(a.get("path"))
        if p == self.root or p.is_dir():
            raise BridgeError("That is a folder.")
        data = base64.b64decode(a.get("data") or "")
        p.parent.mkdir(parents=True, exist_ok=True)
        with open(p, "ab" if a.get("append") else "wb") as f:
            f.write(data)
        return {"size": p.stat().st_size}

    def op_mkdir(self, a):
        self.path(a.get("path")).mkdir(parents=True, exist_ok=True)
        return {}

    def op_delete(self, a):
        p = self.path(a.get("path"), True)
        if p == self.root:
            raise BridgeError("The project folder itself can't be deleted.")
        dest = self.trash / time.strftime("%Y%m%d-%H%M%S") / self.rel(p)
        dest.parent.mkdir(parents=True, exist_ok=True)
        shutil.move(str(p), str(dest))
        return {"trash": self.rel(dest)}

    def op_move(self, a):
        s, d = self.path(a.get("from"), True), self.path(a.get("to"))
        if s == self.root:
            raise BridgeError("The project folder itself can't be moved.")
        d.parent.mkdir(parents=True, exist_ok=True)
        shutil.move(str(s), str(d))
        return {}

    def op_search(self, a):
        base = self.path(a.get("root"), True)
        pat, needle, limit = (a.get("pattern") or "*").lower(), (a.get("contains") or ""), int(a.get("max") or 100)
        rx = re.compile(re.escape(needle), re.I) if needle else None
        hits = []
        for p in self._walk(base):
            if p.is_dir() or not fnmatch.fnmatch(p.name.lower(), pat):
                continue
            if rx:
                try:
                    if p.stat().st_size > 2_000_000:
                        continue
                    for i, line in enumerate(p.read_text("utf-8", errors="ignore").splitlines(), 1):
                        if rx.search(line):
                            hits.append({"path": self.rel(p), "line": i, "text": line.strip()[:200]})
                            if len(hits) >= limit:
                                return {"hits": hits}
                except OSError:
                    continue
            else:
                hits.append({"path": self.rel(p)})
                if len(hits) >= limit:
                    break
        return {"hits": hits}

    def op_exec(self, a, user=False):
        cmd = str(a.get("command") or "")
        if not cmd.strip():
            raise BridgeError("No command.")
        low = cmd.lower()
        for pat, what in BLOCKED:
            if (not user or what in ("credential locations", "credential dumping", "formatting drives", "disk changes",
                                     "disk partitioning")) and re.search(pat, low, re.I | re.M):
                raise BridgeError(f"Blocked by the Device Bridge: {what}.")
        cwd = self.path(a.get("cwd") or ".", True)
        timeout = max(1, min(int(a.get("timeout") or 120), 1800))
        if IS_WIN:
            argv = ["powershell.exe", "-NoProfile", "-NonInteractive", "-Command",
                    "[Console]::OutputEncoding=[Text.Encoding]::UTF8; " + cmd]
            flags = subprocess.CREATE_NO_WINDOW
        else:
            argv, flags = ["bash", "-lc", cmd], 0
        t0 = time.time()
        try:
            r = subprocess.run(argv, cwd=cwd, capture_output=True, text=True, encoding="utf-8", errors="replace",
                               timeout=timeout, stdin=subprocess.DEVNULL, creationflags=flags)
            return {"code": r.returncode, "stdout": (r.stdout or "")[-200000:], "stderr": (r.stderr or "")[-50000:],
                    "seconds": round(time.time() - t0, 2)}
        except subprocess.TimeoutExpired as e:
            out = e.stdout.decode("utf-8", "replace") if isinstance(e.stdout, bytes) else (e.stdout or "")
            return {"code": None, "timeout": True, "stdout": out[-200000:], "stderr": "", "seconds": round(time.time() - t0, 2)}


# ====================================================================== HTTP
class State:
    cfg: Config
    project: Project
    code = ""
    fails = 0             # wrong tries for the current code
    total_fails = 0       # wrong tries since start
    code_until = 0.0
    pair_lock = threading.Lock()
    port = 8766


def new_code():
    State.code = f"{secrets.randbelow(10**6):06d}"
    State.fails = 0
    State.code_until = time.time() + CODE_TTL
    print("\n" + "=" * 62, flush=True)
    print(f"   Pairing code for Edgemode Code Studio:   {State.code[:3]} {State.code[3:]}", flush=True)
    print("   (Code Studio > Settings > Project access > Device Bridge)", flush=True)
    print("=" * 62 + "\n", flush=True)


class Handler(BaseHTTPRequestHandler):
    server_version = "EdgemodeBridge/" + VERSION

    def log_message(self, *a):
        pass

    def _origin(self):
        return self.headers.get("Origin", "")

    def _host_ok(self):
        host = (self.headers.get("Host") or "").lower()
        return host in (f"127.0.0.1:{State.port}", f"localhost:{State.port}")

    def _send(self, code, obj):
        body = json.dumps(obj).encode()
        self.send_response(code)
        origin = self._origin()
        if State.cfg.origin_ok(origin):
            self.send_header("Access-Control-Allow-Origin", origin)
            self.send_header("Vary", "Origin")
        self.send_header("Content-Type", "application/json")
        self.send_header("Cache-Control", "no-store")
        self.send_header("Content-Length", str(len(body)))
        self.end_headers()
        self.wfile.write(body)

    def do_OPTIONS(self):
        origin = self._origin()
        if not self._host_ok() or not State.cfg.origin_ok(origin):
            self.send_response(403)
            self.end_headers()
            return
        self.send_response(204)
        self.send_header("Access-Control-Allow-Origin", origin)
        self.send_header("Access-Control-Allow-Methods", "GET, POST, OPTIONS")
        self.send_header("Access-Control-Allow-Headers", "Content-Type, X-Bridge-Token")
        self.send_header("Access-Control-Allow-Private-Network", "true")
        self.send_header("Access-Control-Max-Age", "600")
        self.send_header("Vary", "Origin")
        self.end_headers()

    def _guard(self):
        if not self._host_ok():
            self._send(403, {"error": "unknown host"})
            return False
        if not State.cfg.origin_ok(self._origin()):
            self._send(403, {"error": f"This web address isn't allowed by the Device Bridge: {self._origin() or '(none)'}. "
                                      f"Start the bridge with --allow-origin {self._origin() or '<address>'}"})
            return False
        return True

    def _json(self):
        n = int(self.headers.get("Content-Length") or 0)
        if n > 60 * 1024 * 1024:
            raise BridgeError("Request too large.")
        return json.loads(self.rfile.read(n) or b"{}")

    def do_GET(self):
        if not self._guard():
            return
        if urlparse(self.path).path == "/hello":
            paired = State.cfg.token_ok(self.headers.get("X-Bridge-Token", ""), self._origin())
            return self._send(200, {"bridge": "edgemode", "version": VERSION,
                                    "folder": State.project.root.name if paired else "",
                                    "paired": paired, "exec": True, "shell": "PowerShell" if IS_WIN else "bash",
                                    "os": f"{platform.system()} {platform.release()}"})
        self._send(404, {"error": "not found"})

    def do_POST(self):
        if not self._guard():
            return
        path = urlparse(self.path).path
        try:
            j = self._json()
        except (ValueError, BridgeError) as e:
            return self._send(400, {"error": str(e)})
        if path == "/pair":
            return self._pair(j)
        if path == "/rpc":
            if not State.cfg.token_ok(self.headers.get("X-Bridge-Token", ""), self._origin()):
                return self._send(401, {"error": "Not paired with this Device Bridge (pair again in Settings)."})
            op, args = str(j.get("op", "")), j.get("args") or {}
            fn = getattr(State.project, "op_" + op, None) if re.fullmatch(r"[a-z]+", op) else None
            if not fn:
                return self._send(400, {"error": f"Unknown operation {op}"})
            user = bool(j.get("user")) and op == "exec"      # only your own Terminal commands skip the agent's blocks
            what = args.get("command") if op == "exec" else args.get("path") or args.get("root") or args.get("from") or ""
            log(f"{'you  ' if j.get('user') else 'agent'} {op:6} {str(what)[:120]}")
            try:
                res = fn(args, user=True) if user else fn(args)
                return self._send(200, {"result": res})
            except BridgeError as e:
                log(f"      refused: {e}")
                return self._send(200, {"error": str(e)})
            except Exception as e:  # noqa: BLE001
                return self._send(200, {"error": f"{type(e).__name__}: {e}"})
        self._send(404, {"error": "not found"})

    def _pair(self, j):
        """One pairing try at a time; wrong codes are slow, limited per code and per bridge run."""
        code = re.sub(r"\D", "", str(j.get("code", "")))[:6]
        with State.pair_lock:
            if State.total_fails >= MAX_PAIR_FAILS:
                return self._send(429, {"error": "Pairing is off after too many wrong codes. "
                                                 "Restart the Device Bridge to get a new code."})
            if time.time() > State.code_until:
                log("The pairing code expired: a new code was made.")
                new_code()
                return self._send(401, {"error": "That pairing code expired. Use the new code in the Device Bridge window."})
            if len(code) == 6 and secrets.compare_digest(code, State.code):
                token = State.cfg.add_token(norm_origin(self._origin()), str(j.get("name", "Code Studio")))
                log(f"Paired with {self._origin()}")
                new_code()
                return self._send(200, {"token": token, "folder": State.project.root.name})
            State.fails += 1
            State.total_fails += 1
            log(f"Wrong pairing code from {self._origin()} ({State.total_fails}/{MAX_PAIR_FAILS})")
            time.sleep(1.5)        # holds the lock: at most one guess per 1.5 s
            if State.total_fails >= MAX_PAIR_FAILS:
                State.code = ""
                log("Too many wrong codes: pairing is OFF until you restart the Device Bridge.")
            elif State.fails >= CODE_TRIES:
                log("Too many wrong codes: a new code was made.")
                new_code()
            return self._send(401, {"error": "Wrong pairing code. Check the code in the Device Bridge window."})


class Server(ThreadingHTTPServer):
    allow_reuse_address = False
    daemon_threads = True

    def server_bind(self):
        import socket
        if hasattr(socket, "SO_EXCLUSIVEADDRUSE"):
            self.socket.setsockopt(socket.SOL_SOCKET, socket.SO_EXCLUSIVEADDRUSE, 1)
        super().server_bind()


def choose_folder(cfg: Config, given: str | None) -> Path:
    if given:
        p = Path(given).expanduser()
    else:
        last = cfg.data.get("folder")
        p = None
        if last and Path(last).is_dir():
            ans = input(f"Share the project folder {last}? [Y/n] ").strip().lower()
            if ans in ("", "y", "yes"):
                p = Path(last)
        if p is None:
            try:
                import tkinter
                from tkinter import filedialog
                tk = tkinter.Tk()
                tk.withdraw()
                tk.attributes("-topmost", True)
                chosen = filedialog.askdirectory(title="Choose the project folder to share with Edgemode Code Studio")
                tk.destroy()
                p = Path(chosen) if chosen else None
            except Exception:  # noqa: BLE001
                p = None
        if p is None:
            p = Path(input("Project folder to share: ").strip().strip('"')).expanduser()
    p = p.resolve()
    if not p.is_dir():
        sys.exit(f"Not a folder: {p}")
    if p == Path(p.anchor) or p == HOME.resolve() or any(is_under(p, d) or is_under(d, p) for d in PROTECTED):
        sys.exit("Choose a project folder, not a whole drive, your user folder or a system/credential folder.")
    cfg.data["folder"] = str(p)
    cfg.save()
    return p


def main():
    ap = argparse.ArgumentParser(description="Edgemode Device Bridge")
    ap.add_argument("--folder")
    ap.add_argument("--port", type=int, default=8766)
    ap.add_argument("--allow-origin", action="append", default=[],
                    help="extra Code Studio web address to accept, exactly as https://host[:port] (no wildcards)")
    ap.add_argument("--forget-pairings", action="store_true")
    a = ap.parse_args()
    cfg = Config()
    for raw in a.allow_origin:
        o = norm_origin(raw)
        if not o:
            sys.exit(f"--allow-origin {raw}: give one exact address like https://studio.example.com "
                     "(https; http only for 127.0.0.1/localhost; no wildcards or paths).")
        if o not in cfg.data["origins"]:
            cfg.data["origins"].append(o)
    if a.forget_pairings:
        cfg.data["tokens"] = {}
    cfg.save()
    State.cfg, State.port = cfg, a.port
    State.project = Project(choose_folder(cfg, a.folder))
    try:
        srv = Server(("127.0.0.1", a.port), Handler)
    except OSError:
        sys.exit(f"Port {a.port} is in use (is the Device Bridge already running?). Use --port <number>.")
    print(f"Edgemode Device Bridge {VERSION}", flush=True)
    print(f"Sharing project folder: {State.project.root}", flush=True)
    print(f"Listening on http://127.0.0.1:{a.port} (only this PC). Accepted web apps: {', '.join(cfg.data['origins'])}",
          flush=True)
    print("Close this window to stop sharing.", flush=True)
    new_code()
    try:
        srv.serve_forever()
    except KeyboardInterrupt:
        pass


def _started_by_double_click() -> bool:
    if not IS_WIN:
        return False
    try:
        import ctypes
        return ctypes.windll.kernel32.GetConsoleProcessList((ctypes.c_uint * 4)(), 4) <= 2   # only us (+ py launcher)
    except Exception:  # noqa: BLE001
        return False


if __name__ == "__main__":
    pause = _started_by_double_click()
    try:
        main()
    except SystemExit as e:
        if e.code not in (None, 0):
            print(e.code, flush=True)
    finally:
        if pause:
            input("\nPress Enter to close this window...")
