#!/usr/bin/env python3
from __future__ import annotations
import re
import shutil
import subprocess
import sys
from pathlib import Path

if len(sys.argv) != 2:
    raise SystemExit("Usage: configure-nginx.py /etc/nginx/sites-available/vixon.fr")

path = Path(sys.argv[1]).resolve()
if not path.is_file():
    raise SystemExit(f"Fichier Nginx introuvable : {path}")

include_line = "    include /etc/nginx/snippets/vxbot-location.conf;"
text = path.read_text()
if "vxbot-location.conf" in text:
    print("Configuration VX BOT déjà présente dans Nginx.")
    raise SystemExit(0)

lines = text.splitlines()
depth = 0
stack: list[dict[str, int | bool]] = []
blocks: list[dict[str, int | bool]] = []

for index, original in enumerate(lines):
    line = original.split('#', 1)[0]
    before = depth
    if re.match(r"^\s*server\s*\{", line):
        stack.append({"start": index, "start_depth": before, "domain": False, "ssl": False})

    if stack:
        if re.search(r"\bserver_name\b[^;]*\bvixon\.fr\b", line):
            stack[-1]["domain"] = True
        if re.search(r"\blisten\b[^;]*(443|ssl)", line):
            stack[-1]["ssl"] = True

    depth += line.count('{') - line.count('}')

    if stack and depth == stack[-1]["start_depth"] and '}' in line:
        block = stack.pop()
        block["end"] = index
        blocks.append(block)

targets = [block for block in blocks if block["domain"]]
if not targets:
    raise SystemExit("Aucun bloc server_name vixon.fr trouvé. Ajoute manuellement l’include Nginx indiqué dans le README.")

target = next((block for block in targets if block["ssl"]), targets[0])
insert_at = int(target["end"])
lines.insert(insert_at, include_line)
new_text = "\n".join(lines) + "\n"

backup = path.with_suffix(path.suffix + ".vxbot-backup")
shutil.copy2(path, backup)
path.write_text(new_text)

result = subprocess.run(["nginx", "-t"], text=True, capture_output=True)
if result.returncode != 0:
    shutil.copy2(backup, path)
    print(result.stdout)
    print(result.stderr, file=sys.stderr)
    raise SystemExit("Configuration Nginx invalide : sauvegarde restaurée automatiquement.")

print(f"Route /vxgamesbot/ ajoutée à {path}")
print(f"Sauvegarde : {backup}")
