"""Convert legacy static HTML pages into Django templates for the home app."""
from __future__ import annotations

import re
from pathlib import Path

BASE_DIR = Path(__file__).resolve().parent.parent
TEMPLATE_DIR = BASE_DIR / 'home' / 'templates' / 'home'

PAGES = {
    'index.html': 'index.html',
    'about.html': 'about.html',
    'contact.html': 'contact.html',
    'services.html': 'services.html',
}

URL_MAP = {
    'index.html': "{% url 'home:index' %}",
    'about.html': "{% url 'home:about' %}",
    'contact.html': "{% url 'home:contact' %}",
    'services.html': "{% url 'home:services' %}",
    'jobs.html': "{% url 'jobs:list' %}",
    'companies.html': "{% url 'companies:list' %}",
    'jobseekers.html': "{% url 'seekers:list' %}",
    'blog.html': "{% url 'blog:list' %}",
    'podcast.html': "{% url 'podcast:list' %}",
    'subscriptions.html': "{% url 'subscriptions:pricing' %}",
    'testimonials.html': "{% url 'testimonials:list' %}",
    'register.html': "{% url 'accounts:register' %}",
    'login.html': "{% url 'accounts:login' %}",
    'job-details.html': "{% url 'jobs:detail' slug='senior-software-engineer-airtel' %}",
    'company-profile.html': "{% url 'companies:detail' slug='airtel-zambia' %}",
    'candidate-profile.html': "{% url 'seekers:detail' slug='chanda-mwila' %}",
    'blog-post.html': "{% url 'blog:detail' slug='zambia-2025-salary-guide' %}",
    'podcast-episode.html': "{% url 'podcast:detail' slug='ep-24-zambia-salary-landscape' %}",
    'submit-testimonial.html': "{% url 'testimonials:submit' %}",
    'company/post-job.html': "{% url 'employers:post_job' %}",
    'company/dashboard.html': "{% url 'employers:dashboard' %}",
}


def convert_static(text: str) -> str:
    text = text.replace('src="js/', "src=\"{% static 'js/")
    text = text.replace('href="css/', "href=\"{% static 'css/")
    text = text.replace('src="images/', "src=\"{% static 'images/")
    text = text.replace('href="images/', "href=\"{% static 'images/")
    text = text.replace('href="favicon/', "href=\"{% static 'favicon/")
    text = text.replace("url('images/", "url('{% static 'images/")
    text = re.sub(
        r"url\('\{% static 'images/([^']+)'\)",
        r"url('{% static 'images/\1' %}')",
        text,
    )
    text = text.replace("srcset=\"images/", "srcset=\"{% static 'images/")
    text = re.sub(
        r"(src=\"{% static 'js/[^\"]+)(\")",
        r"\1' %}\2",
        text,
    )
    text = re.sub(
        r"(href=\"{% static 'css/[^\"]+)(\")",
        r"\1' %}\2",
        text,
    )
    text = re.sub(
        r"(src=\"{% static 'images/[^\"]+)(\")",
        r"\1' %}\2",
        text,
    )
    text = re.sub(
        r"(href=\"{% static 'images/[^\"]+)(\")",
        r"\1' %}\2",
        text,
    )
    text = re.sub(
        r"(href=\"{% static 'favicon/[^\"]+)(\")",
        r"\1' %}\2",
        text,
    )
    text = re.sub(
        r"(srcset=\"{% static 'images/[^\"]+)(\")",
        r"\1' %}\2",
        text,
    )
    return text


def convert_urls(text: str) -> str:
    for legacy, django_url in URL_MAP.items():
        text = text.replace(f'href="{legacy}"', f'href="{django_url}"')
        text = text.replace(f"href='{legacy}'", f"href='{django_url}'")
        text = text.replace(f"window.location.href = '{legacy}'", f"window.location.href = '{django_url}'")
    return text


def extract_body(html: str) -> tuple[str, str, str, str]:
    title_match = re.search(r'<title>(.*?)</title>', html, re.S)
    title = title_match.group(1).strip() if title_match else 'PEZAJOB'
    style_match = re.search(r'<style>(.*?)</style>', html, re.S)
    extra_css = style_match.group(1).strip() if style_match else ''
    body_match = re.search(r'<body>(.*)</body>', html, re.S)
    body = body_match.group(1).strip() if body_match else html
    body = re.sub(r'<nav class="navbar".*?</nav>', '', body, count=1, flags=re.S)
    body = re.sub(r'<footer class="footer".*?</footer>', '', body, count=1, flags=re.S)
    scripts = '\n'.join(re.findall(r'(<script[\s\S]*?</script>)', body))
    body = re.sub(r'<script[\s\S]*?</script>', '', body)
    body = re.sub(r'<!-- ================ FOOTER ================ -->', '', body)
    body = re.sub(r'<!-- Scroll to Top -->[\s\S]*?<button id="scroll-top"[\s\S]*?</button>', '', body)
    return title, extra_css, body.strip(), scripts


def build_template(name: str, source: Path) -> str:
    html = source.read_text(encoding='utf-8')
    title, extra_css, body, scripts = extract_body(html)
    body = convert_static(convert_urls(body))
    scripts = convert_static(convert_urls(scripts))
    coverflow = 'coverflow.css' in html
    blocks = [
        "{% extends 'home/base.html' %}",
        "{% load static %}",
        f"{{% block title %}}{title}{{% endblock %}}",
    ]
    if extra_css:
        blocks.append('{% block extra_css %}')
        blocks.append(f'<style>{extra_css}</style>')
        blocks.append('{% endblock %}')
    if coverflow:
        blocks.append("{% block extra_head %}<link rel=\"stylesheet\" href=\"{% static 'css/coverflow.css' %}\" />{% endblock %}")
    blocks.extend(['{% block content %}', body, '{% endblock %}'])
    if scripts:
        blocks.extend(['{% block extra_js %}', scripts, '{% endblock %}'])
    return '\n'.join(blocks) + '\n'


def main() -> None:
    TEMPLATE_DIR.mkdir(parents=True, exist_ok=True)
    for source_name, target_name in PAGES.items():
        source = BASE_DIR / source_name
        if not source.exists():
            print(f'Skip missing {source_name}')
            continue
        target = TEMPLATE_DIR / target_name
        target.write_text(build_template(target_name, source), encoding='utf-8')
        print(f'Built {target}')


if __name__ == '__main__':
    main()
