"""Copia templates Flask e converte url_for para Django."""
from __future__ import annotations

import re
import shutil
from pathlib import Path

ROOT = Path(__file__).resolve().parent.parent
FLASK_TPL = Path(r"c:\Repositorios\sysRevisao\app\templates")
DJANGO_TPL = ROOT / "templates"

# Flask endpoint -> Django url name
URL_MAP = {
    "main.home": "core:home",
    "main.about": "core:about",
    "main.help_page": "core:help",
    "main.blog": "core:blog",
    "main.dashboard": "core:dashboard",
    "auth.signup": "accounts:signup",
    "auth.login": "accounts:login",
    "auth.logout": "accounts:logout",
    "auth.profile": "accounts:profile",
    "reviews.index": "reviews:index",
    "reviews.create": "reviews:create",
    "reviews.detail": "reviews:detail",
    "reviews.settings": "reviews:settings",
    "reviews.invite_collaborator": "reviews:invite_collaborator",
    "reviews.remove_collaborator": "reviews:remove_collaborator",
    "reviews.transfer_ownership": "reviews:transfer_ownership",
    "reviews.claim_personal": "reviews:claim_personal",
    "reviews.leave": "reviews:leave",
    "planning.index": "planning:index",
    "planning.protocol": "planning:protocol",
    "planning.quality": "planning:quality",
    "planning.extraction": "planning:extraction",
    "conducting.index": "conducting:index",
    "conducting.search": "conducting:search",
    "conducting.import_studies": "conducting:import_studies",
    "conducting.selection": "conducting:selection",
    "conducting.quality_assessment": "conducting:quality_assessment",
    "conducting.extraction_autosave": "conducting:extraction_autosave",
    "conducting.data_extraction": "conducting:data_extraction",
    "conducting.analysis": "conducting:analysis",
    "conducting.export_articles": "conducting:export_articles",
    "reporting.index": "reporting:index",
    "reporting.export_protocol": "reporting:export_protocol",
    "reporting.export_extraction": "reporting:export_extraction",
    "reporting.thesis_reminders": "reporting:thesis_reminders",
    "reporting.thesis_reminders_print": "reporting:thesis_reminders_print",
    "reporting.export_thesis_reminders": "reporting:export_thesis_reminders",
    "reporting.synthesis": "reporting:synthesis",
    "reporting.synthesis_presentation": "reporting:synthesis_presentation",
    "reporting.export_synthesis_presentation": "reporting:export_synthesis_presentation",
    "reporting.export_synthesis_docx": "reporting:export_synthesis_docx",
    "reporting.export_synthesis_xlsx": "reporting:export_synthesis_xlsx",
    "reporting.export_synthesis_latex": "reporting:export_synthesis_latex",
    "reporting.export_synthesis_latex_abnt": "reporting:export_synthesis_latex_abnt",
    "reporting.export_rsl_complete": "reporting:export_rsl_complete",
    "reporting.export_upe_thesis": "reporting:export_upe_thesis",
    "invites.list_invites": "invites:list",
    "invites.accept": "invites:accept",
    "invites.decline": "invites:decline",
    "slug.review_home": "core:review_home",
    "slug.planning_home": "core:planning_home",
    "slug.conducting_home": "core:conducting_home",
    "slug.reporting_home": "core:reporting_home",
    "public.public_review": "core:public_review",
}


def convert_url_for(text: str) -> str:
    def repl(match: re.Match) -> str:
        endpoint = match.group(1)
        rest = match.group(2) or ""
        django_name = URL_MAP.get(endpoint, endpoint.replace(".", ":"))
        # review_id= -> review_id=
        return "{% url '" + django_name + "'" + rest + " %}"

    text = re.sub(
        r"\{\{\s*url_for\(['\"]([^'\"]+)['\"]([^}]*)\}\}",
        repl,
        text,
    )
    text = re.sub(
        r"url_for\(['\"]([^'\"]+)['\"]([^)]*)\)",
        lambda m: "{% url '" + URL_MAP.get(m.group(1), m.group(1).replace(".", ":")) + "'"
        + m.group(2).replace("review_id=", "review_id=").replace("_anchor=", "#")
        + " %}",
        text,
    )
    text = text.replace(
        "url_for('adminlte.static', filename=",
        "{% static 'adminlte/",
    )
    text = re.sub(
        r"\{\%\s*static\s+'adminlte/([^']+)'\s*\%\}",
        r"{% static 'adminlte/\1' %}",
        text,
    )
    # Fix adminlte static pattern
    text = re.sub(
        r"\{\{\s*\{% static 'adminlte/([^']+)'\s*\%\}\s*\}\}",
        r"{% static 'adminlte/\1' %}",
        text,
    )
    if "{% load static %}" not in text and "static '" in text:
        if text.startswith("<!DOCTYPE") or text.startswith("{% extends"):
            text = "{% load static %}\n" + text
    text = text.replace("form.hidden_tag()", "{% csrf_token %}")
    text = text.replace("|default(false)", "")
    return text


def main() -> None:
    if DJANGO_TPL.exists():
        shutil.rmtree(DJANGO_TPL)
    shutil.copytree(FLASK_TPL, DJANGO_TPL)
    for path in DJANGO_TPL.rglob("*.html"):
        path.write_text(convert_url_for(path.read_text(encoding="utf-8")), encoding="utf-8")
    print(f"Templates ported to {DJANGO_TPL}")


if __name__ == "__main__":
    main()
