"""
academics/admin_report_cards.py

Registers all report-card-related models in the Django admin
with inline editing of monthly marks and term syntheses.

Add to your academics/admin.py:
    from academics.admin_report_cards import *
"""

from django.contrib import admin
from django.utils.html import format_html
from django.urls import reverse

from academics.models_grades import (
    AcademicTerm,
    ReportSubject,
    MonthlyMark,
    TermSynthesis,
    ReportCard,
)
from academics.views_report_cards import admin_generate_class_report_cards


# ─────────────────────────────────────────────────────────────
# Academic Term
# ─────────────────────────────────────────────────────────────

@admin.register(AcademicTerm)
class AcademicTermAdmin(admin.ModelAdmin):
    list_display  = ('__str__', 'academic_year', 'term', 'start_date', 'end_date', 'is_current')
    list_filter   = ('academic_year', 'term', 'is_current')
    list_editable = ('is_current',)
    ordering      = ('-academic_year', 'term')


# ─────────────────────────────────────────────────────────────
# Report Subject Catalogue
# ─────────────────────────────────────────────────────────────

@admin.register(ReportSubject)
class ReportSubjectAdmin(admin.ModelAdmin):
    list_display  = ('report_type', 'domain', 'activity', 'sub_activity', 'order')
    list_filter   = ('report_type', 'domain')
    search_fields = ('sub_activity', 'domain', 'activity')
    ordering      = ('report_type', 'order')


# ─────────────────────────────────────────────────────────────
# Monthly Mark — inline for quick entry
# ─────────────────────────────────────────────────────────────

class MonthlyMarkInline(admin.TabularInline):
    model   = MonthlyMark
    extra   = 0
    fields  = ('subject', 'month_number', 'score', 'entered_by')
    raw_id_fields = ('subject', 'entered_by')
    ordering = ('subject__order', 'month_number')


@admin.register(MonthlyMark)
class MonthlyMarkAdmin(admin.ModelAdmin):
    list_display  = ('student', 'term', 'subject', 'month_number', 'score', 'entered_by')
    list_filter   = ('term', 'subject__report_type', 'month_number')
    search_fields = ('student__first_name', 'student__last_name',
                     'student__student_id', 'subject__sub_activity')
    raw_id_fields = ('student', 'term', 'subject', 'entered_by')
    ordering      = ('term', 'student__last_name', 'subject__order', 'month_number')


# ─────────────────────────────────────────────────────────────
# Term Synthesis — standalone admin
# NOTE: TermSynthesis has no FK to ReportCard (it links via
# student + term), so it cannot be used as an inline on
# ReportCardAdmin. Manage syntheses here directly.
# ─────────────────────────────────────────────────────────────

@admin.register(TermSynthesis)
class TermSynthesisAdmin(admin.ModelAdmin):
    list_display  = ('student', 'term', 'subject', 'synthese_score', 'appreciation', 'remark')
    list_filter   = ('term', 'subject__report_type', 'appreciation')
    search_fields = ('student__first_name', 'student__last_name',
                     'student__student_id', 'subject__sub_activity')
    raw_id_fields = ('student', 'term', 'subject')
    ordering      = ('term', 'student__last_name', 'subject__order')

    # Quick-compute action: recalculate synthese_score from monthly marks
    actions = ['recompute_from_monthly']

    @admin.action(description='♻ Recompute synthese from monthly marks')
    def recompute_from_monthly(self, request, queryset):
        updated = 0
        for ts in queryset:
            ts.compute_from_monthly()
            updated += 1
        self.message_user(request, f'Recomputed {updated} synthesis record(s).')


# ─────────────────────────────────────────────────────────────
# Report Card — main admin with inline marks
# ─────────────────────────────────────────────────────────────

@admin.register(ReportCard)
class ReportCardAdmin(admin.ModelAdmin):
    list_display = (
        'student_name', 'report_type', 'school_class', 'term',
        'average', 'position', 'promotion_status',
        'is_finalised', 'pdf_link', 'pdf_actions'
    )
    list_filter  = (
        'report_type', 'term', 'school_class',
        'promotion_status', 'is_finalised'
    )
    search_fields = (
        'student__first_name', 'student__last_name', 'student__student_id'
    )
    raw_id_fields = ('student', 'term', 'school_class')
    readonly_fields = (
        'total_marks', 'average', 'position', 'total_general',
        'annual_average', 'annual_position',
        'pdf_file', 'generated_at', 'created_at', 'updated_at',
        'pdf_link',
    )
    actions = [admin_generate_class_report_cards]

    fieldsets = (
        ('Student & Term', {
            'fields': ('student', 'term', 'school_class', 'report_type')
        }),
        ('Computed Results', {
            'fields': (
                'total_marks', 'average', 'position', 'total_general',
            ),
            'classes': ('collapse',),
        }),
        ('Annual Results (Term 3)', {
            'fields': (
                'term1_average', 'term2_average', 'term3_average',
                'annual_average', 'annual_position',
            ),
            'classes': ('collapse',),
        }),
        ('Attendance', {
            'fields': ('days_present', 'days_absent', 'days_late'),
            'classes': ('collapse',),
        }),
        ('Comments & Conduct', {
            'fields': (
                'conduct',
                'class_teacher_remark', 'head_teacher_remark',
            ),
        }),
        ('Promotion Decision', {
            'fields': (
                'promotion_status', 'promoted_to_class', 'next_term_begins',
            ),
        }),
        ('Francophone Conduct', {
            'fields': ('discipline_brutal', 'absenteisme', 'barvade'),
            'classes': ('collapse',),
        }),
        ('PDF & Status', {
            'fields': ('is_finalised', 'pdf_file', 'generated_at', 'pdf_link'),
        }),
    )

    inlines = []   # TermSynthesis has no FK to ReportCard — manage via its own admin

    # ── Custom display columns ──

    @admin.display(description='Student', ordering='student__last_name')
    def student_name(self, obj):
        return obj.student.get_full_name()

    @admin.display(description='PDF')
    def pdf_link(self, obj):
        if obj.pdf_file:
            return format_html(
                '<a href="{}" target="_blank">📄 View</a>', obj.pdf_file.url
            )
        return '—'

    @admin.display(description='Actions')
    def pdf_actions(self, obj):
        if obj.pk:
            preview_url = reverse('rc-preview', args=[obj.pk])
            pdf_url = reverse('rc-pdf', args=[obj.pk])
            return format_html(
                '<a href="{}">👁 Preview</a> &nbsp; '
                '<a href="{}">⬇ PDF</a>',
                preview_url, pdf_url
            )
        return '—'