"""Corrige tags {% url %} e static quebradas na portagem Flask → Django."""
from __future__ import annotations

import re
from pathlib import Path

ROOT = Path(__file__).resolve().parent.parent / "templates"


def fix_file(path: Path) -> bool:
    text = path.read_text(encoding="utf-8")
    original = text

    # {% url 'name')  %} → {% url 'name' %}
    text = re.sub(
        r"\{\%\s*url\s+'([^']+)'\)\s*\%\}",
        r"{% url '\1' %}",
        text,
    )
    text = re.sub(
        r"\{\%\s*url\s+'([^']+)',\s*review_id=review\.id\)\s*\%\}",
        r"{% url '\1' review.id %}",
        text,
    )
    text = re.sub(
        r"\{\%\s*url\s+'([^']+)',\s*review_id=review\.id,\s*user_id=([^)]+)\)\s*\%\}",
        r"{% url '\1' review.id \2 %}",
        text,
    )
    text = re.sub(
        r"\{\%\s*url\s+'([^']+)',\s*code=([^,)]+)(?:,\s*_external=True)?\)\s*\%\}",
        r"{% url '\1' \2 %}",
        text,
    )

    # adminlte / static url mistakes
    text = re.sub(
        r"\{\%\s*url\s+'adminlte:static',\s*filename='([^']+)'\)\s*\%\}",
        r"{% static 'adminlte/\1' %}",
        text,
    )
    text = re.sub(
        r"\{\%\s*url\s+'static',\s*filename='([^']+)'\)\s*\%\}",
        r"{% static '\1' %}",
        text,
    )

    # {{ _('key') }} → {% _ 'key' %}
    text = re.sub(r"\{\{\s*_\('([^']+)'\)\s*\}\}", r"{% _ '\1' %}", text)
    text = re.sub(r"\{\{\s*_\(\"([^\"]+)\"\)\s*\}\}", r"{% _ '\1' %}", text)

    # Flask-Login → Django auth
    text = text.replace("current_user.is_authenticated", "user.is_authenticated")
    text = text.replace("current_user.", "user.")

    # request.endpoint → view name (aproximação)
    text = text.replace(
        "request.endpoint",
        "request.resolver_match.view_name",
    )

    if "{% load static %}" not in text and "{% static " in text:
        if text.startswith("{% extends") or text.startswith("{% load"):
            lines = text.split("\n", 1)
            if lines[0].startswith("{% extends"):
                text = lines[0] + "\n{% load static %}\n{% load rsl_i18n %}\n" + lines[1]
            else:
                text = "{% load static %}\n{% load rsl_i18n %}\n" + text
        else:
            text = "{% load static %}\n{% load rsl_i18n %}\n" + text

    if text != original:
        path.write_text(text, encoding="utf-8")
        return True
    return False


def main() -> None:
    n = 0
    for path in ROOT.rglob("*.html"):
        if fix_file(path):
            print(f"fixed: {path.relative_to(ROOT)}")
            n += 1
    print(f"Done. {n} file(s) updated.")


if __name__ == "__main__":
    main()
