#!/usr/bin/env python3
"""Bravo Work: agente local para el modo Work de Bravo Robots AI.

Permite que la IA, con tu permiso, trabaje en las carpetas que elijas de este
equipo: listar y leer archivos, escribir archivos y ejecutar comandos.

Reglas de seguridad (se aplican aquí, en tu equipo, no en el servidor):
  * Solo se accede a las carpetas que autorices. Cualquier ruta fuera de ellas
    (incluidos enlaces simbólicos que apunten fuera) se rechaza.
  * Cada escritura de archivo y cada comando muestra los detalles y espera a
    que escribas "s" en esta terminal. Si no confirmas, no se hace nada.
  * Puedes parar el agente en cualquier momento con Ctrl+C y desemparejar el
    equipo con "unpair" o desde la web.

Uso:
  python bravo_work_agent.py pair --server https://ia-bravorobots.com --code ABCD-EFGH --folder /ruta/proyecto
  python bravo_work_agent.py run
  python bravo_work_agent.py add-folder /otra/ruta
  python bravo_work_agent.py remove-folder /otra/ruta
  python bravo_work_agent.py status
  python bravo_work_agent.py unpair

Solo usa la biblioteca estándar de Python 3.8+ (Windows, macOS y Linux).
"""
import argparse
import difflib
import json
import os
import platform
import socket
import ssl
import stat
import subprocess
import sys
import time
import urllib.error
import urllib.request

VERSION = "1.0.0"
CONFIG_DIR = os.path.join(os.path.expanduser("~"), ".bravo-work")
CONFIG_PATH = os.path.join(CONFIG_DIR, "config.json")
MAX_READ_BYTES = 512 * 1024
MAX_OUTPUT_BYTES = 100 * 1024
MAX_LIST_ENTRIES = 500
DEFAULT_COMMAND_TIMEOUT = 120
MAX_COMMAND_TIMEOUT = 600


# --- Configuración local ----------------------------------------------------
def load_config():
    try:
        with open(CONFIG_PATH, "r", encoding="utf-8") as handle:
            return json.load(handle)
    except FileNotFoundError:
        return None


def save_config(config):
    os.makedirs(CONFIG_DIR, exist_ok=True)
    temporary = CONFIG_PATH + ".tmp"
    with open(temporary, "w", encoding="utf-8") as handle:
        json.dump(config, handle, indent=2, ensure_ascii=False)
    if os.name != "nt":
        os.chmod(temporary, stat.S_IRUSR | stat.S_IWUSR)
    os.replace(temporary, CONFIG_PATH)


def require_config():
    config = load_config()
    if not config or not config.get("token"):
        sys.exit("Este equipo no está emparejado. Usa primero: python bravo_work_agent.py pair --server ... --code ... --folder ...")
    return config


def normalize_folder(folder):
    path = os.path.realpath(os.path.expanduser(folder))
    if not os.path.isdir(path):
        sys.exit(f"La carpeta no existe: {folder}")
    return path


# --- Comunicación con el servidor ---------------------------------------------
class ServerError(Exception):
    def __init__(self, status, message):
        super().__init__(message)
        self.status = status


def api(config, method, path, payload=None, token=None, timeout=40):
    url = config["server"].rstrip("/") + path
    data = json.dumps(payload).encode("utf-8") if payload is not None else None
    headers = {"Accept": "application/json", "User-Agent": f"BravoWork/{VERSION}"}
    if data is not None:
        headers["Content-Type"] = "application/json"
    if token:
        headers["Authorization"] = f"Bearer {token}"
    request = urllib.request.Request(url, data=data, headers=headers, method=method)
    context = None
    if config.get("insecure"):
        context = ssl.create_default_context()
        context.check_hostname = False
        context.verify_mode = ssl.CERT_NONE
    try:
        with urllib.request.urlopen(request, timeout=timeout, context=context) as response:
            body = response.read()
    except urllib.error.HTTPError as exc:
        try:
            message = json.loads(exc.read().decode("utf-8")).get("error") or exc.reason
        except Exception:
            message = exc.reason
        raise ServerError(exc.code, str(message)) from exc
    return json.loads(body.decode("utf-8")) if body else {}


# --- Control de rutas -----------------------------------------------------------
def inside(path, root):
    try:
        return os.path.commonpath([path, root]) == root
    except ValueError:  # Unidades distintas en Windows.
        return False


def resolve_path(raw_path, folders, must_exist=False):
    if not isinstance(raw_path, str) or not raw_path.strip():
        raise PermissionError("Falta la ruta.")
    raw_path = os.path.expanduser(raw_path.strip())
    candidate = raw_path if os.path.isabs(raw_path) else os.path.join(folders[0], raw_path)
    resolved = os.path.realpath(candidate)
    if not any(inside(resolved, root) for root in folders):
        raise PermissionError(
            f"La ruta {raw_path} está fuera de las carpetas autorizadas: " + ", ".join(folders)
        )
    if must_exist and not os.path.exists(resolved):
        raise FileNotFoundError(f"No existe: {raw_path}")
    return resolved


def confirm(title, details):
    print()
    print("=" * 72)
    print(f"  CONFIRMACIÓN REQUERIDA · {title}")
    print("=" * 72)
    print(details)
    print("-" * 72)
    try:
        answer = input("¿Permitir? Escribe «s» para aceptar o Enter para rechazar: ").strip().lower()
    except EOFError:
        return False
    return answer in {"s", "si", "sí", "y", "yes"}


def truncate(text, limit=MAX_OUTPUT_BYTES):
    encoded = text.encode("utf-8", "replace")
    if len(encoded) <= limit:
        return text, False
    return encoded[:limit].decode("utf-8", "ignore"), True


# --- Acciones -------------------------------------------------------------------
def action_list_dir(args, folders, _options):
    path = resolve_path(args.get("path") or folders[0], folders, must_exist=True)
    if not os.path.isdir(path):
        raise NotADirectoryError("La ruta no es una carpeta.")
    entries = []
    names = sorted(os.listdir(path), key=str.lower)
    for name in names[:MAX_LIST_ENTRIES]:
        full = os.path.join(path, name)
        try:
            info = os.stat(full)
            kind = "dir" if stat.S_ISDIR(info.st_mode) else "file"
            entries.append({"name": name, "type": kind, "size": info.st_size if kind == "file" else None})
        except OSError:
            entries.append({"name": name, "type": "unknown", "size": None})
    return {"path": path, "entries": entries, "truncated": len(names) > MAX_LIST_ENTRIES}


def action_read_file(args, folders, options):
    path = resolve_path(args.get("path"), folders, must_exist=True)
    if not os.path.isfile(path):
        raise IsADirectoryError("La ruta no es un archivo.")
    if options.confirm_reads and not confirm("LEER ARCHIVO", f"Archivo: {path}"):
        return {"ok": False, "denied": True, "error": "El usuario rechazó la lectura."}
    size = os.path.getsize(path)
    with open(path, "rb") as handle:
        raw = handle.read(MAX_READ_BYTES)
    if b"\x00" in raw[:8192]:
        return {"path": path, "size": size, "binary": True, "content": ""}
    return {
        "path": path,
        "size": size,
        "binary": False,
        "truncated": size > MAX_READ_BYTES,
        "content": raw.decode("utf-8", "replace"),
    }


def action_write_file(args, folders, _options):
    path = resolve_path(args.get("path"), folders)
    content = args.get("content")
    if not isinstance(content, str):
        raise ValueError("Falta el contenido del archivo.")
    if os.path.isdir(path):
        raise IsADirectoryError("La ruta es una carpeta.")
    previous = None
    if os.path.exists(path):
        with open(path, "r", encoding="utf-8", errors="replace") as handle:
            previous = handle.read()
    if previous is None:
        lines = content.splitlines()
        preview = "\n".join(lines[:40]) + (f"\n… ({len(lines) - 40} líneas más)" if len(lines) > 40 else "")
        details = f"Crear archivo nuevo: {path}\nTamaño: {len(content.encode('utf-8'))} bytes\n\n{preview}"
    else:
        diff = list(
            difflib.unified_diff(previous.splitlines(), content.splitlines(), "actual", "nuevo", lineterm="", n=2)
        )
        shown = "\n".join(diff[:80]) + (f"\n… ({len(diff) - 80} líneas de diferencia más)" if len(diff) > 80 else "")
        details = f"SOBRESCRIBIR archivo existente: {path}\n\n{shown or '(sin cambios)'}"
    if not confirm("ESCRIBIR ARCHIVO", details):
        return {"ok": False, "denied": True, "error": "El usuario rechazó la escritura."}
    os.makedirs(os.path.dirname(path), exist_ok=True)
    # Comprobación repetida tras crear carpetas: evita carreras con enlaces simbólicos.
    resolve_path(path, folders)
    with open(path, "w", encoding="utf-8", newline="") as handle:
        handle.write(content)
    return {"ok": True, "path": path, "bytes": len(content.encode("utf-8")), "created": previous is None}


def action_run_command(args, folders, _options):
    command = args.get("command")
    if not isinstance(command, str) or not command.strip():
        raise ValueError("Falta el comando.")
    cwd = resolve_path(args.get("cwd") or folders[0], folders, must_exist=True)
    if not os.path.isdir(cwd):
        raise NotADirectoryError("El directorio de trabajo no es una carpeta.")
    try:
        timeout = int(args.get("timeout", DEFAULT_COMMAND_TIMEOUT))
    except (TypeError, ValueError):
        timeout = DEFAULT_COMMAND_TIMEOUT
    timeout = max(1, min(timeout, MAX_COMMAND_TIMEOUT))
    details = (
        f"Comando: {command}\nCarpeta: {cwd}\nLímite de tiempo: {timeout} s\n\n"
        "Atención: un comando puede leer o modificar cualquier cosa a la que tenga acceso tu usuario,\n"
        "también fuera de las carpetas autorizadas. Acéptalo solo si entiendes lo que hace."
    )
    if not confirm("EJECUTAR COMANDO", details):
        return {"ok": False, "denied": True, "error": "El usuario rechazó el comando."}
    started = time.monotonic()
    try:
        completed = subprocess.run(
            command, shell=True, cwd=cwd, capture_output=True, timeout=timeout,
            stdin=subprocess.DEVNULL,
        )
    except subprocess.TimeoutExpired as exc:
        stdout, _ = truncate((exc.stdout or b"").decode("utf-8", "replace"))
        stderr, _ = truncate((exc.stderr or b"").decode("utf-8", "replace"))
        return {"ok": False, "timeout": True, "stdout": stdout, "stderr": stderr,
                "error": f"El comando superó {timeout} s y se detuvo."}
    stdout, stdout_cut = truncate(completed.stdout.decode("utf-8", "replace"))
    stderr, stderr_cut = truncate(completed.stderr.decode("utf-8", "replace"))
    return {
        "ok": completed.returncode == 0,
        "exit_code": completed.returncode,
        "stdout": stdout,
        "stderr": stderr,
        "truncated": stdout_cut or stderr_cut,
        "seconds": round(time.monotonic() - started, 2),
    }


ACTIONS = {
    "list_dir": action_list_dir,
    "read_file": action_read_file,
    "write_file": action_write_file,
    "run_command": action_run_command,
}


def execute(action, folders, options):
    handler = ACTIONS.get(action.get("kind"))
    if handler is None:
        return {"ok": False, "error": "Acción desconocida."}
    try:
        result = handler(action.get("args") or {}, folders, options)
        result.setdefault("ok", True)
        return result
    except (PermissionError, FileNotFoundError, NotADirectoryError, IsADirectoryError, ValueError) as exc:
        return {"ok": False, "error": str(exc)}
    except OSError as exc:
        return {"ok": False, "error": f"Error del sistema: {exc}"}


def describe(action):
    args = action.get("args") or {}
    kind = action.get("kind")
    target = args.get("command") if kind == "run_command" else args.get("path", "")
    return f"{kind} {target}".strip()


# --- Comandos de la línea de órdenes ------------------------------------------
def cmd_pair(options):
    folders = [normalize_folder(folder) for folder in options.folder]
    config = {"server": options.server.rstrip("/"), "insecure": options.insecure}
    name = options.name or socket.gethostname()
    platform_name = f"{platform.system()} {platform.release()} ({platform.machine()})"
    try:
        result = api(config, "POST", "/api/work/agent/pair", {
            "code": options.code, "name": name, "platform": platform_name, "folders": folders,
        })
    except ServerError as exc:
        sys.exit(f"No se pudo emparejar: {exc}")
    except urllib.error.URLError as exc:
        sys.exit(f"No se pudo conectar con {config['server']}: {exc.reason}")
    config.update({"token": result["token"], "device_id": result["device_id"], "name": name, "folders": folders})
    save_config(config)
    print(f"Equipo «{name}» emparejado. Carpetas autorizadas:")
    for folder in folders:
        print(f"  - {folder}")
    print("Ahora ejecuta: python bravo_work_agent.py run")


def cmd_run(options):
    config = require_config()
    folders = [os.path.realpath(folder) for folder in config.get("folders", []) if os.path.isdir(folder)]
    if not folders:
        sys.exit("No hay carpetas autorizadas que existan. Añade una con: add-folder RUTA")
    token = config["token"]
    print(f"Bravo Work {VERSION} conectado a {config['server']} como «{config.get('name')}».")
    print("Carpetas autorizadas:")
    for folder in folders:
        print(f"  - {folder}")
    print("Las escrituras y comandos te pedirán confirmación aquí. Ctrl+C para salir.\n")
    backoff = 2
    hello_sent = False
    while True:
        try:
            if not hello_sent:
                api(config, "POST", "/api/work/agent/hello", {"folders": folders}, token=token)
                hello_sent = True
                print("En línea. Esperando peticiones desde el modo Work…")
            response = api(config, "GET", "/api/work/agent/next", token=token, timeout=60)
            backoff = 2
            action = response.get("action")
            if not action:
                continue
            print(f"[{time.strftime('%H:%M:%S')}] Petición: {describe(action)}")
            result = execute(action, folders, options)
            status = "rechazada" if result.get("denied") else ("correcta" if result.get("ok") else "con error")
            print(f"[{time.strftime('%H:%M:%S')}] Acción {status}.")
            api(config, "POST", "/api/work/agent/result", {"action_id": action["id"], "result": result}, token=token)
        except ServerError as exc:
            if exc.status == 401:
                sys.exit(f"El servidor ha desconectado este equipo: {exc}")
            print(f"Error del servidor ({exc.status}): {exc}. Reintento en {backoff} s.")
            hello_sent = False
            time.sleep(backoff)
            backoff = min(backoff * 2, 60)
        except (urllib.error.URLError, socket.timeout, ConnectionError, TimeoutError) as exc:
            print(f"Sin conexión ({getattr(exc, 'reason', exc)}). Reintento en {backoff} s.")
            hello_sent = False
            time.sleep(backoff)
            backoff = min(backoff * 2, 60)


def cmd_add_folder(options):
    config = require_config()
    folder = normalize_folder(options.path)
    if folder not in config["folders"]:
        config["folders"].append(folder)
        save_config(config)
    print("Carpetas autorizadas:\n  - " + "\n  - ".join(config["folders"]))
    print("Reinicia «run» para aplicar el cambio.")


def cmd_remove_folder(options):
    config = require_config()
    folder = os.path.realpath(os.path.expanduser(options.path))
    config["folders"] = [item for item in config["folders"] if item != folder]
    save_config(config)
    print("Carpetas autorizadas:\n  - " + ("\n  - ".join(config["folders"]) or "(ninguna)"))
    print("Reinicia «run» para aplicar el cambio.")


def cmd_status(_options):
    config = load_config()
    if not config:
        print("Este equipo no está emparejado.")
        return
    print(f"Servidor: {config['server']}\nEquipo: {config.get('name')}\nCarpetas:")
    for folder in config.get("folders", []):
        print(f"  - {folder}")


def cmd_unpair(_options):
    config = load_config()
    if not config:
        print("Este equipo no está emparejado.")
        return
    try:
        api(config, "DELETE", "/api/work/agent/device", token=config["token"])
    except (ServerError, urllib.error.URLError) as exc:
        print(f"Aviso: no se pudo avisar al servidor ({exc}); bórralo también desde la web.")
    os.remove(CONFIG_PATH)
    print("Equipo desemparejado y credencial local eliminada.")


def main():
    parser = argparse.ArgumentParser(description="Agente local Bravo Work")
    sub = parser.add_subparsers(dest="command", required=True)
    pair = sub.add_parser("pair", help="Empareja este equipo con tu cuenta")
    pair.add_argument("--server", required=True, help="URL de la web, p. ej. https://ia-bravorobots.com")
    pair.add_argument("--code", required=True, help="Código mostrado en el modo Work")
    pair.add_argument("--folder", action="append", required=True, help="Carpeta autorizada (se puede repetir)")
    pair.add_argument("--name", help="Nombre del equipo")
    pair.add_argument("--insecure", action="store_true", help="No verificar TLS (solo pruebas locales)")
    run = sub.add_parser("run", help="Conecta y atiende peticiones")
    run.add_argument("--confirm-reads", action="store_true", help="Pedir confirmación también para leer archivos")
    add = sub.add_parser("add-folder", help="Autoriza otra carpeta")
    add.add_argument("path")
    remove = sub.add_parser("remove-folder", help="Retira una carpeta autorizada")
    remove.add_argument("path")
    sub.add_parser("status", help="Muestra la configuración")
    sub.add_parser("unpair", help="Desempareja este equipo")
    options = parser.parse_args()
    handlers = {
        "pair": cmd_pair, "run": cmd_run, "add-folder": cmd_add_folder,
        "remove-folder": cmd_remove_folder, "status": cmd_status, "unpair": cmd_unpair,
    }
    try:
        handlers[options.command](options)
    except KeyboardInterrupt:
        print("\nAgente detenido.")


if __name__ == "__main__":
    main()
