"""Settings → Code Editor (super admin only).

Lets the system owner fix the application's code from the browser, without access to the hosting platform.
Safety rails:
  * only the software provider's prime login (set from the server: `python manage.py prime <user>`), never via the UI;
  * only the application's own source files; never the database, uploads, licence, keys or the virtualenv;
  * every save is checked first (Python syntax, template syntax, JSON) and refused if broken;
  * every save keeps the previous version in code_changes, with a diff and one-click restore;
  * a restart is only done after the whole application loads cleanly in a separate test process;
  * `python manage.py code-undo` reverses the last change from the server if the site will not start.
"""
import difflib
import json
import os
import shutil
import subprocess
import sys
import tempfile
import threading
from functools import wraps

from flask import Blueprint, abort, current_app, flash, g, redirect, render_template, request, url_for

from .. import login_required
from ..db import commit, q, x
from ..i18n import t
from ..ledger import audit, now

bp = Blueprint("code", __name__, url_prefix="/setup/code")

BASE = os.path.dirname(os.path.dirname(os.path.dirname(os.path.abspath(__file__))))
ROOTS = ("vertex", "tests", "docs/guide")
TOP_FILES = ("app.py", "manage.py", "requirements.txt", "README.md")
EXTS = (".py", ".html", ".js", ".css", ".json", ".md", ".txt", ".svg")
SKIP_DIRS = {"__pycache__", ".venv", "instance", "node_modules", ".git", "fonts"}
MAX_SIZE = 2 * 1024 * 1024


def superadmin_required(view):
    @wraps(view)
    @login_required
    def wrapped(*args, **kwargs):
        if (g.user["level"] if "level" in g.user.keys() else None) != "prime":
            abort(403)
        return view(*args, **kwargs)
    return wrapped


def files():
    out = list(f for f in TOP_FILES if os.path.isfile(os.path.join(BASE, f)))
    for root in ROOTS:
        for d, dirs, names in os.walk(os.path.join(BASE, root)):
            dirs[:] = sorted(x for x in dirs if x not in SKIP_DIRS and not x.startswith("."))
            for n in sorted(names):
                if n.endswith(EXTS) and os.path.getsize(os.path.join(d, n)) <= MAX_SIZE:
                    out.append(os.path.relpath(os.path.join(d, n), BASE).replace(os.sep, "/"))
    return out


def safe_path(rel):
    """Absolute path of an editable file, or 404. Blocks ../, absolute paths and anything outside the list."""
    rel = (rel or "").replace("\\", "/").lstrip("/")
    if not rel or ".." in rel.split("/") or rel not in set(files()):
        abort(404)
    full = os.path.realpath(os.path.join(BASE, rel))
    if not full.startswith(os.path.realpath(BASE) + os.sep):
        abort(404)
    return rel, full


def read(full):
    with open(full, encoding="utf-8") as f:
        return f.read()


def check(rel, content):
    """None if the file is valid, else a readable error."""
    try:
        if rel.endswith(".py"):
            compile(content, rel, "exec")
        elif rel.endswith(".html") and rel.startswith("vertex/templates/"):
            current_app.jinja_env.parse(content)
        elif rel.endswith(".json"):
            json.loads(content)
    except SyntaxError as e:
        return f"{t('Line')} {e.lineno}: {e.msg}"
    except Exception as e:  # jinja TemplateSyntaxError, json errors
        line = getattr(e, "lineno", None)
        return (f"{t('Line')} {line}: " if line else "") + str(getattr(e, "message", None) or e)
    return None


def write(full, content):
    tmp = full + ".tmp-edit"
    with open(tmp, "w", encoding="utf-8", newline="\n") as f:
        f.write(content)
    os.replace(tmp, full)


def save_change(rel, full, new, note, user_id):
    old = read(full)
    write(full, new)
    cid = x("INSERT INTO code_changes (path, at, user_id, before, after, note) VALUES (?,?,?,?,?,?)",
            (rel, now(), user_id, old, new, note or ""))
    audit(user_id, "update", "code", cid, rel)
    if rel.startswith("vertex/templates/"):
        current_app.jinja_env.cache.clear() if current_app.jinja_env.cache is not None else None
    return cid


def needs_restart():
    """Python files changed since this server process started."""
    started = current_app.config.get("STARTED_AT", "")
    return q("SELECT DISTINCT path FROM code_changes WHERE at >= ? AND (path LIKE '%.py') ORDER BY path", (started,))


def diff_lines(a, b, ra="before", rb="after"):
    return list(difflib.unified_diff((a or "").splitlines(), (b or "").splitlines(), ra, rb, lineterm="", n=3))


@bp.route("/")
@superadmin_required
def index():
    rel = request.args.get("path") or ""
    content = error = None
    if rel:
        rel, full = safe_path(rel)
        content = read(full)
    tree = {}
    for f in files():
        folder = f.rsplit("/", 1)[0] if "/" in f else ""
        tree.setdefault(folder, []).append(f)
    recent = q("SELECT c.id, c.path, c.at, c.note, u.username FROM code_changes c LEFT JOIN users u ON u.id = c.user_id "
               "ORDER BY c.id DESC LIMIT 8")
    return render_template("setup/code.html", tree=tree, path=rel, content=content, error=error, recent=recent,
                           pending=needs_restart())


@bp.route("/save", methods=["POST"])
@superadmin_required
def save():
    rel, full = safe_path(request.form.get("path"))
    new = (request.form.get("content") or "").replace("\r\n", "\n")
    if new == read(full):
        flash(t("No changes to save."), "info")
        return redirect(url_for("code.index", path=rel))
    err = check(rel, new)
    if err:
        flash(t("Not saved — the file has an error.") + " " + err, "error")
        tree = {}
        for f in files():
            tree.setdefault(f.rsplit("/", 1)[0] if "/" in f else "", []).append(f)
        return render_template("setup/code.html", tree=tree, path=rel, content=new, error=err, recent=[],
                               pending=needs_restart()), 400
    save_change(rel, full, new, request.form.get("note"), g.user["id"])
    commit()
    if rel.endswith(".py"):
        flash(t("Saved. Python changes take effect after “Apply & restart”."), "success")
    else:
        flash(t("Saved. The change is live."), "success")
    return redirect(url_for("code.index", path=rel))


@bp.route("/search")
@superadmin_required
def search():
    term = (request.args.get("q") or "").strip()
    hits = []
    if len(term) >= 2:
        low = term.lower()
        for rel in files():
            try:
                for i, line in enumerate(read(os.path.join(BASE, rel)).splitlines(), 1):
                    if low in line.lower():
                        hits.append({"path": rel, "line": i, "text": line.strip()[:200]})
                        if len(hits) >= 300:
                            break
            except UnicodeDecodeError:
                continue
            if len(hits) >= 300:
                break
    return render_template("setup/code_search.html", term=term, hits=hits)


@bp.route("/history")
@superadmin_required
def history():
    rows = q("SELECT c.id, c.path, c.at, c.note, u.username FROM code_changes c LEFT JOIN users u ON u.id = c.user_id "
             "ORDER BY c.id DESC LIMIT 300")
    return render_template("setup/code_history.html", rows=rows, change=None)


@bp.route("/history/<int:cid>")
@superadmin_required
def change(cid):
    c = q("SELECT c.*, u.username FROM code_changes c LEFT JOIN users u ON u.id = c.user_id WHERE c.id = ?",
          (cid,), one=True) or abort(404)
    return render_template("setup/code_history.html", rows=None, change=c,
                           diff=diff_lines(c["before"], c["after"], c["path"] + " (before)", c["path"] + " (after)"))


@bp.route("/history/<int:cid>/restore", methods=["POST"])
@superadmin_required
def restore(cid):
    c = q("SELECT * FROM code_changes WHERE id = ?", (cid,), one=True) or abort(404)
    rel, full = safe_path(c["path"])
    err = check(rel, c["before"])
    if err:
        flash(err, "error")
        return redirect(url_for("code.change", cid=cid))
    save_change(rel, full, c["before"], t("Restored the version before change") + f" #{cid}", g.user["id"])
    commit()
    flash(t("Restored.") + (" " + t("Python changes take effect after “Apply & restart”.") if rel.endswith(".py") else ""),
          "success")
    return redirect(url_for("code.index", path=rel))


def trial_start():
    """Load the whole application in a separate process against a copy of the database. (ok, output)"""
    tmp = tempfile.mkdtemp(prefix="vertex-check-")
    try:
        db = os.path.join(tmp, "check.db")
        shutil.copy(current_app.config["DATABASE"], db)
        code = ("import sys; sys.path.insert(0, %r)\n"
                "from vertex import create_app\n"
                "app = create_app(%r)\n"
                "c = app.test_client()\n"
                "r = c.get('/login')\n"
                "assert r.status_code == 200, r.status_code\n"
                "print('ok')\n") % (BASE, db)
        p = subprocess.run([sys.executable, "-c", code], cwd=BASE, capture_output=True, text=True, timeout=120)
        out = (p.stdout + p.stderr).strip()
        return p.returncode == 0 and out.endswith("ok"), out[-4000:]
    except subprocess.TimeoutExpired:
        return False, t("The application took too long to start.")
    finally:
        shutil.rmtree(tmp, ignore_errors=True)


def restart_process():
    """Replace this server process with a fresh one running the new code (same command line)."""
    def go():
        import time
        time.sleep(1.0)
        os.execv(sys.executable, [sys.executable] + sys.argv)
    threading.Thread(target=go, daemon=True).start()


@bp.route("/restart", methods=["POST"])
@superadmin_required
def restart():
    ok, out = trial_start()
    if not ok:
        flash(t("Restart cancelled — the application does not start with the current code. Fix or restore the last "
                "change first. The running system was not touched."), "error")
        return render_template("setup/code_check.html", out=out), 400
    audit(g.user["id"], "restart", "code", None, "apply & restart")
    commit()
    if current_app.config.get("TESTING"):
        flash(t("Check passed."), "success")
        return redirect(url_for("code.index"))
    restart_process()
    return render_template("setup/code_restart.html")


@bp.route("/check", methods=["POST"])
@superadmin_required
def check_all():
    problems = []
    for rel in files():
        if rel.endswith((".py", ".html", ".json")):
            err = check(rel, read(os.path.join(BASE, rel)))
            if err:
                problems.append((rel, err))
    ok, out = trial_start()
    return render_template("setup/code_check.html", out=out, ok=ok, problems=problems, checked=True)
