from django.conf import settings
from django.http import Http404, HttpResponse
from django.shortcuts import get_object_or_404
from django.template import engines
from django.views.decorators.http import require_GET

from api.models import TtPos, TtStudent


PAGE_TEMPLATE = """<!doctype html>
<html lang="en"><head><meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>Student POS Options — {{ student.code }}</title>
<style>
body{margin:0;background:#f5f7fb;color:#172033;font-family:Arial,sans-serif}main{max-width:1100px;margin:32px auto;padding:0 20px 48px}h1{margin-bottom:6px}.muted{color:#667085}.term,.pos{background:white;border:1px solid #dfe4ec;border-radius:10px}.term{margin-top:24px;padding:20px}.pos{margin-top:14px;padding:16px}.group{margin:14px 0 0 28px;padding-left:16px;border-left:3px solid #dfe4ec}.module{margin:8px 0 0 20px}.selected{color:#067647;font-weight:700}.not-selected{color:#667085}code{background:#eef2f7;padding:2px 6px;border-radius:4px}
</style></head><body><main>
<h1>{{ student.name }}</h1>
<div class="muted">Student: <code>{{ student.code }}</code> · ID {{ student.id }}</div>
{% for section in term_sections %}
<section class="term"><h2>{{ section.academic_term.name }}</h2>
<div class="muted">Academic term: <code>{{ section.academic_term.code }}</code> · ID {{ section.academic_term.id }}</div>
{% for pos in section.positions %}
<article class="pos"><div class="{% if pos.selected %}selected{% else %}not-selected{% endif %}">
{% if pos.selected %}✓{% else %}○{% endif %} POS: {{ pos.name }} · <code>{{ pos.code }}</code> · ID {{ pos.id }}</div>
{% for group in pos.module_groups %}
<div class="group"><strong>{{ group.module_group.name }}</strong>
<span class="muted">· <code>{{ group.code }}</code> · relation ID {{ group.id }}</span>
{% for module in group.modules %}
<div class="module {% if module.selected %}selected{% else %}not-selected{% endif %}">
{% if module.selected %}✓{% else %}○{% endif %} {{ module.name }} · <code>{{ module.code }}</code> · module ID {{ module.id }} · relation ID {{ module.relation_id }}</div>
{% empty %}<div class="module muted">No modules found.</div>{% endfor %}</div>
{% empty %}<p class="muted">No module groups found.</p>{% endfor %}</article>
{% empty %}<p class="muted">No POS options found.</p>{% endfor %}</section>
{% empty %}<section class="term muted">No academic terms found for this student.</section>{% endfor %}
</main></body></html>"""


@require_GET
def get_student_pos_details(request, student_code):
    """Local/development browser view of a student's POS/module options."""
    remote_address = request.META.get("REMOTE_ADDR", "")
    if not settings.DEBUG and remote_address not in {"127.0.0.1", "::1"}:
        raise Http404

    student = get_object_or_404(TtStudent, code=student_code)
    academic_terms = list(student.academic_term.all().order_by("code"))
    selected_pos_ids = set(student.pos.values_list("id", flat=True))
    selected_pos_module_ids = set(student.pos_module.values_list("id", flat=True))

    positions = (
        TtPos.objects
        .filter(academic_term_id__in=[term.id for term in academic_terms])
        .select_related("academic_term")
        .prefetch_related(
            "ttposmodulegroup_set__module_group",
            "ttposmodulegroup_set__ttposmodulegroupmodule_set__module",
        )
        .order_by("academic_term__code", "code")
    )

    positions_by_term = {term.id: [] for term in academic_terms}
    for pos in positions:
        module_groups = []
        for pos_module_group in pos.ttposmodulegroup_set.all():
            modules = [{
                "relation_id": pos_module.id,
                "id": pos_module.module.id,
                "code": pos_module.module.code,
                "name": pos_module.module.name,
                "selected": pos_module.id in selected_pos_module_ids,
            } for pos_module in pos_module_group.ttposmodulegroupmodule_set.all()]
            module_groups.append({
                "id": pos_module_group.id,
                "code": pos_module_group.code,
                "module_group": pos_module_group.module_group,
                "modules": modules,
            })

        positions_by_term.setdefault(pos.academic_term_id, []).append({
            "id": pos.id,
            "code": pos.code,
            "name": pos.name,
            "selected": pos.id in selected_pos_ids,
            "module_groups": module_groups,
        })

    term_sections = [{
        "academic_term": term,
        "positions": positions_by_term.get(term.id, []),
    } for term in academic_terms]

    template = engines["django"].from_string(PAGE_TEMPLATE)
    html = template.render({
        "student": student,
        "term_sections": term_sections,
    }, request)
    return HttpResponse(html)
