#!/usr/bin/env python3
"""
Painel de reinício remoto de serviços (PM2, Firebird, Apache) via SSH.

- Python 3.8+ puro (sem dependências). Usa o cliente `ssh` do sistema.
- Banco SQLite em ./data/painel.db (usuários, servidores, serviços, logs).
- Perfis: viewer (só vê) < operator (reinicia) < admin (gerencia tudo).

Uso:
    python3 app.py                       # inicia o painel
    python3 app.py --reset-password USER # redefine a senha de um usuário
    DEMO=1 python3 app.py                # modo demonstração (não usa SSH)
"""
import csv
import getpass
import hashlib
import hmac
import io
import json
import os
import random
import re
import secrets
import shlex
import sqlite3
import subprocess
import sys
import threading
import time
import traceback
from concurrent.futures import ThreadPoolExecutor
from contextlib import contextmanager
from datetime import datetime, timezone
from http.cookies import SimpleCookie
from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer
from urllib.parse import parse_qs, urlparse

# ----------------------------------------------------------------------------
# Configuração (variáveis de ambiente)
# ----------------------------------------------------------------------------
BASE = os.path.dirname(os.path.abspath(__file__))
DATA_DIR = os.environ.get("DATA_DIR", os.path.join(BASE, "data"))
DB_PATH = os.path.join(DATA_DIR, "painel.db")
TEXT_LOG = os.path.join(DATA_DIR, "restart.log")
KNOWN_HOSTS = os.path.join(DATA_DIR, "known_hosts")
HOST = os.environ.get("HOST", "127.0.0.1")
PORT = int(os.environ.get("PORT", "8080"))
DEFAULT_KEY = os.environ.get("SSH_KEY", os.path.expanduser("~/.ssh/id_ed25519"))
DEMO = os.environ.get("DEMO") == "1"
SESSION_HOURS = int(os.environ.get("SESSION_HOURS", "8"))
SSH_TIMEOUT = int(os.environ.get("SSH_TIMEOUT", "90"))
APACHE_CONFIGTEST = os.environ.get("APACHE_CONFIGTEST", "1") != "0"
COOKIE_SECURE = os.environ.get("COOKIE_SECURE") == "1"      # use =1 atrás de HTTPS
TRUST_PROXY = os.environ.get("TRUST_PROXY") == "1"           # lê X-Forwarded-For
MAX_OUT = 20000

ROLE_LEVEL = {"viewer": 1, "operator": 2, "admin": 3}
KINDS = ("pm2", "firebird", "apache")

RE_HOST = re.compile(r"^[A-Za-z0-9][A-Za-z0-9._:-]{0,252}$")
RE_USER = re.compile(r"^[a-z_][a-z0-9_-]{0,31}$")
RE_UNIT = re.compile(r"^[A-Za-z0-9@._-]{1,64}$")
RE_PM2 = re.compile(r"^[A-Za-z0-9][A-Za-z0-9 ._:@-]{0,63}$")
RE_KEY = re.compile(r"^/[^\0\n\r]{1,300}$")
RE_LOGIN = re.compile(r"^[A-Za-z0-9._-]{3,40}$")

PM2_PRE = 'export NVM_DIR="$HOME/.nvm"; [ -s "$NVM_DIR/nvm.sh" ] && . "$NVM_DIR/nvm.sh"; '


def now_iso():
    return datetime.now(timezone.utc).strftime("%Y-%m-%dT%H:%M:%SZ")


# ----------------------------------------------------------------------------
# Banco de dados
# ----------------------------------------------------------------------------
SCHEMA = """
CREATE TABLE IF NOT EXISTS users(
  id INTEGER PRIMARY KEY AUTOINCREMENT,
  username TEXT NOT NULL UNIQUE COLLATE NOCASE,
  name TEXT NOT NULL,
  pw_hash TEXT NOT NULL,
  role TEXT NOT NULL CHECK(role IN ('viewer','operator','admin')),
  active INTEGER NOT NULL DEFAULT 1,
  created_at TEXT NOT NULL,
  last_login TEXT
);
CREATE TABLE IF NOT EXISTS sessions(
  token_hash TEXT PRIMARY KEY,
  user_id INTEGER NOT NULL REFERENCES users(id) ON DELETE CASCADE,
  expires TEXT NOT NULL
);
CREATE TABLE IF NOT EXISTS servers(
  id INTEGER PRIMARY KEY AUTOINCREMENT,
  name TEXT NOT NULL UNIQUE,
  host TEXT NOT NULL,
  port INTEGER NOT NULL DEFAULT 22,
  ssh_user TEXT NOT NULL,
  ssh_key TEXT,
  notes TEXT
);
CREATE TABLE IF NOT EXISTS services(
  id INTEGER PRIMARY KEY AUTOINCREMENT,
  server_id INTEGER NOT NULL REFERENCES servers(id) ON DELETE CASCADE,
  kind TEXT NOT NULL CHECK(kind IN ('pm2','firebird','apache')),
  target TEXT NOT NULL,
  last_status TEXT,
  last_detail TEXT,
  last_checked TEXT,
  UNIQUE(server_id, kind, target)
);
CREATE TABLE IF NOT EXISTS restart_logs(
  id INTEGER PRIMARY KEY AUTOINCREMENT,
  ts TEXT NOT NULL,
  user_id INTEGER,
  username TEXT NOT NULL,
  server_id INTEGER,
  server_name TEXT NOT NULL,
  host TEXT NOT NULL,
  kind TEXT NOT NULL,
  target TEXT NOT NULL,
  command TEXT,
  reason TEXT,
  status_before TEXT,
  status_after TEXT,
  exit_code INTEGER,
  success INTEGER NOT NULL,
  duration_ms INTEGER,
  output TEXT
);
CREATE INDEX IF NOT EXISTS idx_logs_ts ON restart_logs(ts DESC);
CREATE INDEX IF NOT EXISTS idx_logs_server ON restart_logs(server_name);
"""


@contextmanager
def db():
    conn = sqlite3.connect(DB_PATH, timeout=30)
    conn.row_factory = sqlite3.Row
    conn.execute("PRAGMA foreign_keys=ON")
    try:
        yield conn
        conn.commit()
    except Exception:
        conn.rollback()
        raise
    finally:
        conn.close()


def init_db():
    os.makedirs(DATA_DIR, exist_ok=True)
    with db() as c:
        c.execute("PRAGMA journal_mode=WAL")
        c.executescript(SCHEMA)


# ----------------------------------------------------------------------------
# Senhas e sessões
# ----------------------------------------------------------------------------
def hash_pw(pw, salt=None, iters=300_000):
    salt = salt or secrets.token_bytes(16)
    dk = hashlib.pbkdf2_hmac("sha256", pw.encode(), salt, iters)
    return "pbkdf2$%d$%s$%s" % (iters, salt.hex(), dk.hex())


def check_pw(pw, stored):
    try:
        _, iters, salt, digest = stored.split("$")
        dk = hashlib.pbkdf2_hmac("sha256", pw.encode(), bytes.fromhex(salt), int(iters))
        return hmac.compare_digest(dk.hex(), digest)
    except Exception:
        return False


DUMMY_HASH = hash_pw("dummy-password")


def sha(s):
    return hashlib.sha256(s.encode()).hexdigest()


def create_session(conn, user_id):
    token = secrets.token_urlsafe(32)
    exp = datetime.fromtimestamp(time.time() + SESSION_HOURS * 3600, timezone.utc).strftime("%Y-%m-%dT%H:%M:%SZ")
    conn.execute("DELETE FROM sessions WHERE expires < ?", (now_iso(),))
    conn.execute("INSERT INTO sessions(token_hash,user_id,expires) VALUES(?,?,?)", (sha(token), user_id, exp))
    return token


FAILS = {}  # "ip|user" -> [contagem, bloqueado_até]
FAILS_LOCK = threading.Lock()


def throttle_check(key):
    with FAILS_LOCK:
        f = FAILS.get(key)
        if f and f[1] > time.time():
            raise ApiError(429, "Muitas tentativas. Aguarde alguns minutos.")


def throttle_fail(key):
    with FAILS_LOCK:
        f = FAILS.setdefault(key, [0, 0])
        f[0] += 1
        if f[0] >= 5:
            f[0], f[1] = 0, time.time() + 300


def throttle_ok(key):
    with FAILS_LOCK:
        FAILS.pop(key, None)


# ----------------------------------------------------------------------------
# Execução remota via SSH
# ----------------------------------------------------------------------------
def run_remote(srv, remote_cmd, timeout=SSH_TIMEOUT):
    """Retorna (exit_code, stdout, stderr). exit 255 = falha de conexão SSH."""
    key = srv["ssh_key"] or DEFAULT_KEY
    args = [
        "ssh", "-o", "BatchMode=yes", "-o", "ConnectTimeout=10",
        "-o", "StrictHostKeyChecking=accept-new", "-o", "UserKnownHostsFile=" + KNOWN_HOSTS,
        "-o", "IdentitiesOnly=yes", "-o", "ServerAliveInterval=5",
        "-p", str(srv["port"]), "-i", key,
        "%s@%s" % (srv["ssh_user"], srv["host"]), remote_cmd,
    ]
    try:
        p = subprocess.run(args, capture_output=True, text=True, timeout=timeout, stdin=subprocess.DEVNULL)
        return p.returncode, p.stdout, p.stderr
    except subprocess.TimeoutExpired:
        return 124, "", "Tempo esgotado (%ds) aguardando o comando remoto." % timeout
    except FileNotFoundError:
        return 127, "", "Cliente 'ssh' não encontrado no servidor do painel (instale openssh-client)."


def pm2_cmd(inner):
    return "bash -lc " + shlex.quote(PM2_PRE + inner)


def restart_command(kind, target):
    if kind == "pm2":
        return pm2_cmd("pm2 restart %s" % shlex.quote(target))
    unit = shlex.quote(target)
    core = "{ sudo -n systemctl reset-failed %s 2>/dev/null; sudo -n systemctl restart %s; }" % (unit, unit)
    if kind == "apache" and APACHE_CONFIGTEST:
        return "sudo -n apache2ctl configtest && " + core
    return core


def parse_pm2(out):
    for line in reversed(out.strip().splitlines()):
        line = line.strip()
        if line.startswith("["):
            try:
                return json.loads(line)
            except ValueError:
                continue
    return None


def check_service(srv, svc):
    """Retorna dict(state, detail, code). state: online|offline|parcial|erro."""
    if DEMO:
        return demo_check(srv, svc)
    kind, target = svc["kind"], svc["target"]
    if kind == "pm2":
        code, out, err = run_remote(srv, pm2_cmd("pm2 jlist 2>/dev/null"), 30)
        if code != 0:
            return {"state": "erro", "detail": (err or out).strip()[:300] or "código %d" % code, "code": code}
        apps = parse_pm2(out)
        if apps is None:
            return {"state": "erro", "detail": "Saída inválida do 'pm2 jlist' (PM2 instalado para este usuário?)", "code": code}
        sel = apps if target == "all" else [a for a in apps if a.get("name") == target or str(a.get("pm_id")) == target]
        if not sel:
            return {"state": "erro", "detail": "App não encontrado no PM2", "code": 0}
        on = [a for a in sel if (a.get("pm2_env") or {}).get("status") == "online"]
        detail = "%d/%d online" % (len(on), len(sel))
        state = "online" if len(on) == len(sel) else ("offline" if not on else "parcial")
        return {"state": state, "detail": detail, "code": 0}
    code, out, err = run_remote(srv, "systemctl is-active %s" % shlex.quote(target), 30)
    word = out.strip().splitlines()[0] if out.strip() else ""
    if code in (255, 124, 127) or not word:
        return {"state": "erro", "detail": err.strip()[:300] or "sem resposta (código %d)" % code, "code": code}
    if word == "active":
        return {"state": "online", "detail": "active", "code": 0}
    if word in ("activating", "reloading"):
        return {"state": "parcial", "detail": word, "code": 0}
    return {"state": "offline", "detail": word, "code": 0}


# ---- modo demonstração ------------------------------------------------------
DEMO_STATE = {}


def demo_check(srv, svc):
    if srv["host"] == "10.0.0.99":
        time.sleep(0.4)
        return {"state": "erro", "detail": "ssh: connect to host 10.0.0.99 port 22: Connection timed out", "code": 255}
    time.sleep(random.uniform(0.1, 0.4))
    st = DEMO_STATE.setdefault(svc["id"], "online" if random.random() > 0.2 else "offline")
    return {"state": st, "detail": {"online": "active", "offline": "failed"}[st], "code": 0}


def demo_restart(srv, svc):
    time.sleep(1.2)
    if srv["host"] == "10.0.0.99":
        return 255, "", "ssh: connect to host 10.0.0.99 port 22: Connection timed out"
    DEMO_STATE[svc["id"]] = "online"
    if svc["kind"] == "pm2":
        return 0, "[PM2] Applying action restartProcessId on app [%s](ids: [ 0 ])\n[PM2] [%s](0) ✓\n" % (svc["target"], svc["target"]), ""
    if svc["kind"] == "apache":
        return 0, "Syntax OK\n", ""
    return 0, "", ""


# ----------------------------------------------------------------------------
# Utilidades da API
# ----------------------------------------------------------------------------
class ApiError(Exception):
    def __init__(self, status, msg):
        super().__init__(msg)
        self.status, self.msg = status, msg


class Raw:
    def __init__(self, data, ctype, filename=None):
        self.data, self.ctype, self.filename = data, ctype, filename


ROUTES = []


def route(method, pattern, role=None):
    def deco(fn):
        ROUTES.append((method, re.compile("^" + pattern + "$"), role, fn))
        return fn
    return deco


def gq(q, k):
    return (q.get(k) or [""])[0].strip()


def need(body, key, maxlen=200):
    v = body.get(key)
    if not isinstance(v, str) or not v.strip():
        raise ApiError(400, "Campo obrigatório: %s" % key)
    v = v.strip()
    if len(v) > maxlen:
        raise ApiError(400, "Campo '%s' muito longo" % key)
    return v


def validate_target(kind, target):
    if kind not in KINDS:
        raise ApiError(400, "Tipo de serviço inválido")
    target = (target or "").strip()
    if kind == "pm2":
        if target != "all" and not RE_PM2.match(target):
            raise ApiError(400, "Nome de app PM2 inválido (use letras, números, . _ - : @)")
    elif not RE_UNIT.match(target):
        raise ApiError(400, "Nome de unit systemd inválido")
    return target


def clean_server_fields(body):
    name = need(body, "name", 60)
    host = need(body, "host", 253)
    if not RE_HOST.match(host):
        raise ApiError(400, "Host/IP inválido")
    try:
        port = int(body.get("port") or 22)
    except (TypeError, ValueError):
        raise ApiError(400, "Porta inválida")
    if not 1 <= port <= 65535:
        raise ApiError(400, "Porta inválida")
    user = need(body, "ssh_user", 32)
    if not RE_USER.match(user):
        raise ApiError(400, "Usuário SSH inválido")
    key = (body.get("ssh_key") or "").strip() or None
    if key and not RE_KEY.match(key):
        raise ApiError(400, "Caminho da chave deve ser absoluto (ex.: /home/painel/.ssh/id_ed25519)")
    notes = (body.get("notes") or "").strip()[:300]
    return name, host, port, user, key, notes


def servers_payload(conn, admin, only_id=None):
    where, args = ("WHERE id=?", (only_id,)) if only_id else ("", ())
    servers = conn.execute("SELECT * FROM servers %s ORDER BY name COLLATE NOCASE" % where, args).fetchall()
    svcs = conn.execute("SELECT * FROM services ORDER BY kind, target").fetchall()
    by = {}
    for s in svcs:
        by.setdefault(s["server_id"], []).append({
            "id": s["id"], "kind": s["kind"], "target": s["target"], "state": s["last_status"],
            "detail": s["last_detail"], "checked": s["last_checked"]})
    out = []
    for s in servers:
        d = {"id": s["id"], "name": s["name"], "host": s["host"], "port": s["port"],
             "ssh_user": s["ssh_user"], "notes": s["notes"] or "", "services": by.get(s["id"], [])}
        if admin:
            d["ssh_key"] = s["ssh_key"] or ""
        out.append(d)
    return out


def user_public(u):
    return {"id": u["id"], "username": u["username"], "name": u["name"], "role": u["role"],
            "active": bool(u["active"]), "last_login": u["last_login"], "created_at": u["created_at"]}


def active_admins(conn, excluding=None):
    q = "SELECT COUNT(*) FROM users WHERE role='admin' AND active=1"
    a = ()
    if excluding:
        q += " AND id<>?"
        a = (excluding,)
    return conn.execute(q, a).fetchone()[0]


def check_password_rules(pw):
    if not isinstance(pw, str) or len(pw) < 8:
        raise ApiError(400, "A senha deve ter pelo menos 8 caracteres")
    if len(pw) > 200:
        raise ApiError(400, "Senha muito longa")


# ----------------------------------------------------------------------------
# Rotas: autenticação
# ----------------------------------------------------------------------------
@route("POST", r"/api/login")
def api_login(h, user, m, q, body):
    username = str(body.get("username") or "").strip()
    password = str(body.get("password") or "")
    key = "%s|%s" % (h.client_ip(), username.lower())
    throttle_check(key)
    with db() as c:
        u = c.execute("SELECT * FROM users WHERE username=?", (username,)).fetchone()
        ok = check_pw(password, u["pw_hash"] if u else DUMMY_HASH)
        if not (u and ok and u["active"]):
            throttle_fail(key)
            raise ApiError(401, "Usuário ou senha incorretos")
        throttle_ok(key)
        token = create_session(c, u["id"])
        c.execute("UPDATE users SET last_login=? WHERE id=?", (now_iso(), u["id"]))
        h.set_session_cookie(token)
        return {"user": user_public(u)}


@route("POST", r"/api/logout", "viewer")
def api_logout(h, user, m, q, body):
    with db() as c:
        c.execute("DELETE FROM sessions WHERE token_hash=?", (sha(h.session_token() or ""),))
    h.set_session_cookie("", clear=True)
    return {"ok": True}


@route("GET", r"/api/me", "viewer")
def api_me(h, user, m, q, body):
    return {"user": user_public(user), "demo": DEMO}


@route("POST", r"/api/password", "viewer")
def api_password(h, user, m, q, body):
    old, new = str(body.get("old") or ""), body.get("new")
    check_password_rules(new)
    with db() as c:
        row = c.execute("SELECT pw_hash FROM users WHERE id=?", (user["id"],)).fetchone()
        if not check_pw(old, row["pw_hash"]):
            raise ApiError(400, "Senha atual incorreta")
        c.execute("UPDATE users SET pw_hash=? WHERE id=?", (hash_pw(new), user["id"]))
        # encerra as outras sessões do usuário
        c.execute("DELETE FROM sessions WHERE user_id=? AND token_hash<>?", (user["id"], sha(h.session_token() or "")))
    return {"ok": True}


# ----------------------------------------------------------------------------
# Rotas: usuários (admin)
# ----------------------------------------------------------------------------
@route("GET", r"/api/users", "admin")
def api_users(h, user, m, q, body):
    with db() as c:
        return {"users": [user_public(u) for u in c.execute("SELECT * FROM users ORDER BY username COLLATE NOCASE")]}


@route("POST", r"/api/users", "admin")
def api_user_create(h, user, m, q, body):
    username = need(body, "username", 40)
    if not RE_LOGIN.match(username):
        raise ApiError(400, "Login deve ter 3-40 caracteres (letras, números, . _ -)")
    name = need(body, "name", 80)
    role = body.get("role")
    if role not in ROLE_LEVEL:
        raise ApiError(400, "Perfil inválido")
    check_password_rules(body.get("password"))
    try:
        with db() as c:
            cur = c.execute("INSERT INTO users(username,name,pw_hash,role,active,created_at) VALUES(?,?,?,?,1,?)",
                            (username, name, hash_pw(body["password"]), role, now_iso()))
            return {"id": cur.lastrowid}
    except sqlite3.IntegrityError:
        raise ApiError(409, "Já existe um usuário com esse login")


@route("PUT", r"/api/users/(\d+)", "admin")
def api_user_update(h, user, m, q, body):
    uid = int(m.group(1))
    with db() as c:
        u = c.execute("SELECT * FROM users WHERE id=?", (uid,)).fetchone()
        if not u:
            raise ApiError(404, "Usuário não encontrado")
        name = need(body, "name", 80) if "name" in body else u["name"]
        role = body.get("role", u["role"])
        active = 1 if body.get("active", bool(u["active"])) else 0
        if role not in ROLE_LEVEL:
            raise ApiError(400, "Perfil inválido")
        if uid == user["id"] and (role != "admin" or not active):
            raise ApiError(400, "Você não pode remover seu próprio acesso de administrador")
        if u["role"] == "admin" and (role != "admin" or not active) and active_admins(c, uid) == 0:
            raise ApiError(400, "É necessário manter ao menos um administrador ativo")
        c.execute("UPDATE users SET name=?, role=?, active=? WHERE id=?", (name, role, active, uid))
        if body.get("password"):
            check_password_rules(body["password"])
            c.execute("UPDATE users SET pw_hash=? WHERE id=?", (hash_pw(body["password"]), uid))
            c.execute("DELETE FROM sessions WHERE user_id=?", (uid,))
        if not active:
            c.execute("DELETE FROM sessions WHERE user_id=?", (uid,))
    return {"ok": True}


@route("DELETE", r"/api/users/(\d+)", "admin")
def api_user_delete(h, user, m, q, body):
    uid = int(m.group(1))
    if uid == user["id"]:
        raise ApiError(400, "Você não pode excluir seu próprio usuário")
    with db() as c:
        u = c.execute("SELECT * FROM users WHERE id=?", (uid,)).fetchone()
        if not u:
            raise ApiError(404, "Usuário não encontrado")
        if u["role"] == "admin" and u["active"] and active_admins(c, uid) == 0:
            raise ApiError(400, "É necessário manter ao menos um administrador ativo")
        c.execute("DELETE FROM users WHERE id=?", (uid,))  # logs mantêm o nome (snapshot)
    return {"ok": True}


# ----------------------------------------------------------------------------
# Rotas: servidores e serviços
# ----------------------------------------------------------------------------
@route("GET", r"/api/servers", "viewer")
def api_servers(h, user, m, q, body):
    with db() as c:
        return {"servers": servers_payload(c, user["role"] == "admin")}


@route("POST", r"/api/servers", "admin")
def api_server_create(h, user, m, q, body):
    name, host, port, ssh_user, key, notes = clean_server_fields(body)
    services = body.get("services") or []
    clean = []
    for s in services:
        clean.append((s.get("kind"), validate_target(s.get("kind"), s.get("target"))))
    try:
        with db() as c:
            cur = c.execute("INSERT INTO servers(name,host,port,ssh_user,ssh_key,notes) VALUES(?,?,?,?,?,?)",
                            (name, host, port, ssh_user, key, notes))
            for kind, target in clean:
                c.execute("INSERT OR IGNORE INTO services(server_id,kind,target) VALUES(?,?,?)", (cur.lastrowid, kind, target))
            return {"id": cur.lastrowid}
    except sqlite3.IntegrityError:
        raise ApiError(409, "Já existe um servidor com esse nome")


@route("PUT", r"/api/servers/(\d+)", "admin")
def api_server_update(h, user, m, q, body):
    sid = int(m.group(1))
    name, host, port, ssh_user, key, notes = clean_server_fields(body)
    try:
        with db() as c:
            cur = c.execute("UPDATE servers SET name=?,host=?,port=?,ssh_user=?,ssh_key=?,notes=? WHERE id=?",
                            (name, host, port, ssh_user, key, notes, sid))
            if cur.rowcount == 0:
                raise ApiError(404, "Servidor não encontrado")
    except sqlite3.IntegrityError:
        raise ApiError(409, "Já existe um servidor com esse nome")
    return {"ok": True}


@route("DELETE", r"/api/servers/(\d+)", "admin")
def api_server_delete(h, user, m, q, body):
    with db() as c:
        c.execute("DELETE FROM servers WHERE id=?", (int(m.group(1)),))
    return {"ok": True}


@route("POST", r"/api/servers/(\d+)/services", "admin")
def api_service_add(h, user, m, q, body):
    sid = int(m.group(1))
    kind = body.get("kind")
    target = validate_target(kind, body.get("target"))
    with db() as c:
        if not c.execute("SELECT 1 FROM servers WHERE id=?", (sid,)).fetchone():
            raise ApiError(404, "Servidor não encontrado")
        try:
            cur = c.execute("INSERT INTO services(server_id,kind,target) VALUES(?,?,?)", (sid, kind, target))
        except sqlite3.IntegrityError:
            raise ApiError(409, "Esse serviço já está cadastrado neste servidor")
        return {"id": cur.lastrowid}


@route("DELETE", r"/api/services/(\d+)", "admin")
def api_service_delete(h, user, m, q, body):
    with db() as c:
        c.execute("DELETE FROM services WHERE id=?", (int(m.group(1)),))
    return {"ok": True}


def save_status(conn, svc_id, res):
    conn.execute("UPDATE services SET last_status=?, last_detail=?, last_checked=? WHERE id=?",
                 (res["state"], (res.get("detail") or "")[:300], now_iso(), svc_id))


@route("POST", r"/api/servers/(\d+)/status", "viewer")
def api_server_status(h, user, m, q, body):
    sid = int(m.group(1))
    with db() as c:
        srv = c.execute("SELECT * FROM servers WHERE id=?", (sid,)).fetchone()
        if not srv:
            raise ApiError(404, "Servidor não encontrado")
        svcs = c.execute("SELECT * FROM services WHERE server_id=?", (sid,)).fetchall()
    with ThreadPoolExecutor(max_workers=6) as ex:
        results = list(ex.map(lambda s: check_service(srv, s), svcs))
    with db() as c:
        for s, r in zip(svcs, results):
            save_status(c, s["id"], r)
        return {"server": servers_payload(c, user["role"] == "admin", sid)[0]}


# ----------------------------------------------------------------------------
# Rota: reinício
# ----------------------------------------------------------------------------
RESTART_LOCKS = set()
RESTART_GUARD = threading.Lock()


def log_to_file(row):
    try:
        out = (row["output"] or "").replace("\n", " | ")[:400]
        line = "%s user=%s server=%s(%s) service=%s:%s ok=%d exit=%s before=%s after=%s dur=%dms reason=%r out=%s\n" % (
            row["ts"], row["username"], row["server_name"], row["host"], row["kind"], row["target"],
            row["success"], row["exit_code"], row["status_before"], row["status_after"],
            row["duration_ms"], row["reason"], out)
        with open(TEXT_LOG, "a", encoding="utf-8") as f:
            f.write(line)
    except OSError:
        pass


def log_public(r, with_output=True):
    d = {k: r[k] for k in ("id", "ts", "username", "server_name", "host", "kind", "target", "reason",
                           "status_before", "status_after", "exit_code", "duration_ms")}
    d["success"] = bool(r["success"])
    if with_output:
        d["command"] = r["command"]
        d["output"] = r["output"]
    return d


@route("POST", r"/api/services/(\d+)/restart", "operator")
def api_restart(h, user, m, q, body):
    sid = int(m.group(1))
    reason = str(body.get("reason") or "").strip()[:300]
    with db() as c:
        svc = c.execute("SELECT * FROM services WHERE id=?", (sid,)).fetchone()
        if not svc:
            raise ApiError(404, "Serviço não encontrado")
        srv = c.execute("SELECT * FROM servers WHERE id=?", (svc["server_id"],)).fetchone()
    with RESTART_GUARD:
        if sid in RESTART_LOCKS:
            raise ApiError(409, "Já existe um reinício em andamento para este serviço")
        RESTART_LOCKS.add(sid)
    try:
        t0 = time.time()
        cmd = restart_command(svc["kind"], svc["target"])
        before = check_service(srv, svc)
        if before["state"] == "erro" and before["code"] in (255, 124, 127):
            code, out, err = before["code"], "", before["detail"]
            after = before
            cmd = "(reinício não executado: sem conexão SSH)"
        else:
            code, out, err = demo_restart(srv, svc) if DEMO else run_remote(srv, cmd)
            time.sleep(0.2 if DEMO else 2)
            after = check_service(srv, svc) if code != 255 else {"state": "erro", "detail": err, "code": 255}
        ok_states = ("online", "parcial") if (svc["kind"] == "pm2" and svc["target"] == "all") else ("online",)
        success = code == 0 and after["state"] in ok_states
        output = out.rstrip()
        if err.strip():
            output += ("\n" if output else "") + "[stderr]\n" + err.rstrip()
        if not output:
            output = "(sem saída)"
        output += "\n\n[estado após reinício] %s - %s" % (after["state"], after.get("detail") or "")
        if len(output) > MAX_OUT:
            output = output[:MAX_OUT] + "\n…(truncado)"
        dur = int((time.time() - t0) * 1000)
        with db() as c:
            cur = c.execute(
                """INSERT INTO restart_logs(ts,user_id,username,server_id,server_name,host,kind,target,command,reason,
                   status_before,status_after,exit_code,success,duration_ms,output) VALUES(?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)""",
                (now_iso(), user["id"], user["username"], srv["id"], srv["name"], srv["host"], svc["kind"], svc["target"],
                 cmd, reason, before["state"], after["state"], code, 1 if success else 0, dur, output))
            save_status(c, sid, after)
            row = c.execute("SELECT * FROM restart_logs WHERE id=?", (cur.lastrowid,)).fetchone()
        log_to_file(row)
        return {"log": log_public(row), "service": {"id": sid, "state": after["state"], "detail": after.get("detail"),
                                                    "checked": now_iso()}}
    finally:
        with RESTART_GUARD:
            RESTART_LOCKS.discard(sid)


# ----------------------------------------------------------------------------
# Rotas: logs
# ----------------------------------------------------------------------------
def logs_where(q):
    w, p = [], []
    for field, col in (("server", "server_name"), ("kind", "kind"), ("user", "username")):
        v = gq(q, field)
        if v:
            w.append(col + "=?")
            p.append(v)
    if gq(q, "ok") in ("0", "1"):
        w.append("success=?")
        p.append(int(gq(q, "ok")))
    if gq(q, "from"):
        w.append("ts>=?")
        p.append(gq(q, "from"))
    if gq(q, "to"):
        w.append("ts<=?")
        p.append(gq(q, "to"))
    t = gq(q, "q")
    if t:
        like = "%" + t.replace("\\", "\\\\").replace("%", "\\%").replace("_", "\\_") + "%"
        w.append("(output LIKE ? ESCAPE '\\' OR target LIKE ? ESCAPE '\\' OR reason LIKE ? ESCAPE '\\' OR server_name LIKE ? ESCAPE '\\')")
        p += [like] * 4
    return (" WHERE " + " AND ".join(w)) if w else "", p


@route("GET", r"/api/logs", "viewer")
def api_logs(h, user, m, q, body):
    where, p = logs_where(q)
    try:
        limit = max(1, min(200, int(gq(q, "limit") or 50)))
        offset = max(0, int(gq(q, "offset") or 0))
    except ValueError:
        raise ApiError(400, "Paginação inválida")
    with db() as c:
        total = c.execute("SELECT COUNT(*) FROM restart_logs" + where, p).fetchone()[0]
        rows = c.execute("SELECT * FROM restart_logs" + where + " ORDER BY id DESC LIMIT ? OFFSET ?", p + [limit, offset]).fetchall()
    return {"total": total, "logs": [log_public(r, False) for r in rows]}


@route("GET", r"/api/logs/meta", "viewer")
def api_logs_meta(h, user, m, q, body):
    with db() as c:
        return {
            "servers": [r[0] for r in c.execute("SELECT DISTINCT server_name FROM restart_logs ORDER BY 1 COLLATE NOCASE")],
            "users": [r[0] for r in c.execute("SELECT DISTINCT username FROM restart_logs ORDER BY 1 COLLATE NOCASE")],
        }


@route("GET", r"/api/logs/(\d+)", "viewer")
def api_log_one(h, user, m, q, body):
    with db() as c:
        r = c.execute("SELECT * FROM restart_logs WHERE id=?", (int(m.group(1)),)).fetchone()
    if not r:
        raise ApiError(404, "Log não encontrado")
    return {"log": log_public(r)}


def csv_cell(v):
    s = "" if v is None else str(v)
    return "'" + s if s[:1] in ("=", "+", "-", "@", "\t", "\r") else s


@route("GET", r"/api/logs\.csv", "viewer")
def api_logs_csv(h, user, m, q, body):
    where, p = logs_where(q)
    with db() as c:
        rows = c.execute("SELECT * FROM restart_logs" + where + " ORDER BY id DESC LIMIT 50000", p).fetchall()
    buf = io.StringIO()
    w = csv.writer(buf)
    w.writerow(["id", "data_hora_utc", "usuario", "servidor", "host", "servico", "alvo", "estado_antes", "estado_depois",
                "sucesso", "exit_code", "duracao_ms", "motivo", "comando", "saida"])
    for r in rows:
        w.writerow([csv_cell(x) for x in (r["id"], r["ts"], r["username"], r["server_name"], r["host"], r["kind"], r["target"],
                                          r["status_before"], r["status_after"], "sim" if r["success"] else "nao",
                                          r["exit_code"], r["duration_ms"], r["reason"], r["command"], r["output"])])
    return Raw(("﻿" + buf.getvalue()).encode("utf-8"), "text/csv; charset=utf-8",
               "logs-reinicio-%s.csv" % datetime.now().strftime("%Y%m%d-%H%M%S"))


# ----------------------------------------------------------------------------
# Servidor HTTP
# ----------------------------------------------------------------------------
STATIC = {
    "/": ("index.html", "text/html; charset=utf-8"),
    "/static/app.js": ("app.js", "application/javascript; charset=utf-8"),
    "/static/style.css": ("style.css", "text/css; charset=utf-8"),
}
SEC_HEADERS = {
    "X-Content-Type-Options": "nosniff",
    "X-Frame-Options": "DENY",
    "Referrer-Policy": "no-referrer",
    "Content-Security-Policy": "default-src 'self'; style-src 'self'; script-src 'self'; img-src 'self' data:; frame-ancestors 'none'",
}


class Handler(BaseHTTPRequestHandler):
    server_version = "PainelReinicios"
    protocol_version = "HTTP/1.1"

    def log_message(self, fmt, *args):
        if os.environ.get("ACCESS_LOG") == "1":
            sys.stderr.write("%s - %s\n" % (self.client_ip(), fmt % args))

    # -- helpers --
    def client_ip(self):
        if TRUST_PROXY:
            xf = self.headers.get("X-Forwarded-For")
            if xf:
                # o último valor é o que o NOSSO proxy acrescentou (o primeiro pode ser forjado pelo cliente)
                return xf.split(",")[-1].strip()
        return self.client_address[0]

    def session_token(self):
        raw = self.headers.get("Cookie")
        if not raw:
            return None
        try:
            c = SimpleCookie(raw)
            return c["session"].value if "session" in c else None
        except Exception:
            return None

    def set_session_cookie(self, token, clear=False):
        parts = ["session=%s" % token, "Path=/", "HttpOnly", "SameSite=Strict"]
        parts.append("Max-Age=0" if clear else "Max-Age=%d" % (SESSION_HOURS * 3600))
        if COOKIE_SECURE:
            parts.append("Secure")
        self._cookie = "; ".join(parts)

    def current_user(self):
        tok = self.session_token()
        if not tok:
            return None
        with db() as c:
            row = c.execute("""SELECT u.* FROM sessions s JOIN users u ON u.id=s.user_id
                               WHERE s.token_hash=? AND s.expires>? AND u.active=1""", (sha(tok), now_iso())).fetchone()
            if row:
                exp = datetime.fromtimestamp(time.time() + SESSION_HOURS * 3600, timezone.utc).strftime("%Y-%m-%dT%H:%M:%SZ")
                c.execute("UPDATE sessions SET expires=? WHERE token_hash=?", (exp, sha(tok)))
            return row

    def _send(self, status, data, ctype, extra=None):
        self.send_response(status)
        self.send_header("Content-Type", ctype)
        self.send_header("Content-Length", str(len(data)))
        for k, v in SEC_HEADERS.items():
            self.send_header(k, v)
        self.send_header("Cache-Control", "no-store")
        if getattr(self, "_cookie", None):
            self.send_header("Set-Cookie", self._cookie)
        for k, v in (extra or {}).items():
            self.send_header(k, v)
        self.end_headers()
        self.wfile.write(data)

    def send_json(self, obj, status=200):
        self._send(status, json.dumps(obj, ensure_ascii=False).encode("utf-8"), "application/json; charset=utf-8")

    def read_json(self):
        try:
            n = int(self.headers.get("Content-Length") or 0)
        except ValueError:
            n = 0
        if n > 1_000_000:
            raise ApiError(413, "Requisição muito grande")
        if n == 0:
            return {}
        try:
            data = json.loads(self.rfile.read(n).decode("utf-8"))
        except ValueError:
            raise ApiError(400, "JSON inválido")
        if not isinstance(data, dict):
            raise ApiError(400, "JSON inválido")
        return data

    def serve_static(self, path):
        name, ctype = STATIC[path]
        try:
            with open(os.path.join(BASE, "static", name), "rb") as f:
                data = f.read()
        except OSError:
            return self.send_json({"error": "arquivo não encontrado"}, 404)
        self._send(200, data, ctype)

    # -- dispatch --
    def dispatch(self, method):
        self._cookie = None
        u = urlparse(self.path)
        path = u.path
        try:
            if method == "GET" and path in STATIC:
                return self.serve_static(path)
            if not path.startswith("/api/"):
                return self.send_json({"error": "não encontrado"}, 404)
            if method != "GET" and self.headers.get("X-Requested-With") != "fetch":
                raise ApiError(403, "Requisição inválida")
            for mth, rx, role, fn in ROUTES:
                mt = rx.match(path)
                if mth != method or not mt:
                    continue
                user = None
                if role:
                    user = self.current_user()
                    if not user:
                        raise ApiError(401, "Sessão expirada. Entre novamente.")
                    if ROLE_LEVEL[user["role"]] < ROLE_LEVEL[role]:
                        raise ApiError(403, "Sem permissão para esta ação")
                body = self.read_json() if method in ("POST", "PUT") else {}
                res = fn(self, user, mt, parse_qs(u.query), body)
                if isinstance(res, Raw):
                    extra = {"Content-Disposition": 'attachment; filename="%s"' % res.filename} if res.filename else {}
                    return self._send(200, res.data, res.ctype, extra)
                return self.send_json(res)
            raise ApiError(404, "Rota não encontrada")
        except ApiError as e:
            self.send_json({"error": e.msg}, e.status)
        except (BrokenPipeError, ConnectionResetError):
            pass
        except Exception:
            traceback.print_exc()
            self.send_json({"error": "Erro interno do servidor"}, 500)

    def do_GET(self): self.dispatch("GET")
    def do_POST(self): self.dispatch("POST")
    def do_PUT(self): self.dispatch("PUT")
    def do_DELETE(self): self.dispatch("DELETE")


# ----------------------------------------------------------------------------
# Inicialização
# ----------------------------------------------------------------------------
def seed_admin():
    with db() as c:
        if c.execute("SELECT COUNT(*) FROM users").fetchone()[0]:
            return
        pw = os.environ.get("ADMIN_PASSWORD") or ("admin12345" if DEMO else secrets.token_urlsafe(9))
        c.execute("INSERT INTO users(username,name,pw_hash,role,active,created_at) VALUES('admin','Administrador',?, 'admin',1,?)",
                  (hash_pw(pw), now_iso()))
        print("=" * 60)
        print(" Usuário inicial criado:  admin  /  %s" % pw)
        print(" Troque a senha após o primeiro acesso.")
        print("=" * 60, flush=True)
        if DEMO:
            for u, n, r, p in (("operador", "Operador Demo", "operator", "operador123"), ("leitor", "Leitor Demo", "viewer", "leitor123")):
                c.execute("INSERT INTO users(username,name,pw_hash,role,active,created_at) VALUES(?,?,?,?,1,?)",
                          (u, n, hash_pw(p), r, now_iso()))
            print(" DEMO: operador/operador123  e  leitor/leitor123", flush=True)


def seed_demo():
    with db() as c:
        if c.execute("SELECT COUNT(*) FROM servers").fetchone()[0]:
            return
        data = [
            ("ERP-Matriz", "192.168.0.10", "deploy", [("pm2", "api-erp"), ("pm2", "worker-nfe"), ("firebird", "firebird3.0"), ("apache", "apache2")]),
            ("Site-Producao", "192.168.0.20", "deploy", [("pm2", "all"), ("apache", "apache2")]),
            ("BD-Firebird-01", "192.168.0.30", "painel", [("firebird", "firebird3.0")]),
            ("ERP-Filial-02", "10.0.0.99", "deploy", [("pm2", "api-erp"), ("firebird", "firebird3.0"), ("apache", "apache2")]),
        ]
        for name, host, user, svcs in data:
            cur = c.execute("INSERT INTO servers(name,host,port,ssh_user,notes) VALUES(?,?,22,?,?)", (name, host, user, ""))
            for k, t in svcs:
                c.execute("INSERT INTO services(server_id,kind,target) VALUES(?,?,?)", (cur.lastrowid, k, t))


def reset_password(username):
    init_db()
    with db() as c:
        u = c.execute("SELECT id FROM users WHERE username=?", (username,)).fetchone()
        if not u:
            sys.exit("Usuário não encontrado: %s" % username)
        pw = getpass.getpass("Nova senha (mín. 8 caracteres): ")
        if len(pw) < 8 or pw != getpass.getpass("Repita a senha: "):
            sys.exit("Senha inválida ou diferente.")
        c.execute("UPDATE users SET pw_hash=?, active=1 WHERE id=?", (hash_pw(pw), u["id"]))
        c.execute("DELETE FROM sessions WHERE user_id=?", (u["id"],))
    print("Senha atualizada.")


def main():
    if len(sys.argv) == 3 and sys.argv[1] == "--reset-password":
        return reset_password(sys.argv[2])
    init_db()
    seed_admin()
    if DEMO:
        seed_demo()
    httpd = ThreadingHTTPServer((HOST, PORT), Handler)
    httpd.daemon_threads = True
    print("Painel de Reinícios em http://%s:%d  %s" % (HOST, PORT, "[MODO DEMO - sem SSH]" if DEMO else ""), flush=True)
    try:
        httpd.serve_forever()
    except KeyboardInterrupt:
        print("\nEncerrando.")


if __name__ == "__main__":
    main()
