from __future__ import annotations

from django import forms

from apps.mel.reports.models import (
    ComplianceAlert,
    Report,
    ReportDistributionWebhook,
    ReportTemplate,
)


class ReportTemplateForm(forms.ModelForm):
    class Meta:
        model = ReportTemplate
        fields = [
            "name",
            "slug",
            "description",
            "report_type",
            "logframe",
            "sections",
            "schedule_cron",
            "default_recipients",
            "is_active",
        ]
        labels = {"logframe": "Strategic Objective"}
        widgets = {
            # Hidden — populated by the Alpine.js section-picker in the template.
            "sections": forms.HiddenInput(),
            # Hidden — populated by the Alpine.js cron builder in the template.
            "schedule_cron": forms.HiddenInput(),
        }

    def __init__(self, *args, **kwargs):
        super().__init__(*args, **kwargs)
        # C-D5 — scope the default-recipients picker to MEL-relevant / staff
        # users instead of the full ~16k user table (searchable via Select2).
        if "default_recipients" in self.fields:
            from apps.mel.reports.services import mel_recipient_users

            self.fields["default_recipients"].queryset = mel_recipient_users()


class ReportGenerateForm(forms.Form):
    """Form for the Report "generate now" action — picks template + period."""

    template = forms.ModelChoiceField(
        queryset=ReportTemplate.objects.filter(is_active=True),
        widget=forms.Select(
            attrs={"data-s2": True, "data-s2-placeholder": "Search templates…"}
        ),
    )
    period_label = forms.CharField(
        max_length=40,
        help_text="e.g. 2026-Q2",
        widget=forms.TextInput(attrs={"list": "report-period-options", "autocomplete": "off"}),
    )
    period_start = forms.DateField(widget=forms.DateInput(attrs={"type": "date"}))
    period_end = forms.DateField(widget=forms.DateInput(attrs={"type": "date"}))
    narrative = forms.CharField(
        widget=forms.Textarea(attrs={"rows": 3}),
        required=False,
    )

    def clean(self):
        cleaned = super().clean()
        start = cleaned.get("period_start")
        end = cleaned.get("period_end")
        if start and end and end < start:
            raise forms.ValidationError("Period end cannot be before period start.")
        return cleaned


class ReportNarrativeForm(forms.ModelForm):
    class Meta:
        model = Report
        fields = ["narrative"]
        widgets = {"narrative": forms.Textarea(attrs={"rows": 6})}


class ReportDistributionWebhookForm(forms.ModelForm):
    """G18 — admin form for managing webhook endpoints."""

    class Meta:
        model = ReportDistributionWebhook
        fields = ["name", "url", "template", "secret", "is_active"]
        widgets = {
            "secret": forms.TextInput(
                attrs={"placeholder": "Leave blank to auto-generate"},
            ),
            "template": forms.Select(
                attrs={"data-s2": True, "data-s2-placeholder": "Search templates…"}
            ),
        }
        help_texts = {
            "template": "Leave blank to fire on every published report (global).",
            "secret": "HMAC-SHA256 signing key. Receivers verify the X-IILMP-Signature header.",
        }


class ComplianceAlertCreateForm(forms.ModelForm):
    """M&E SRS Table 66 — manual compliance review.

    Lets a Compliance Officer record an issue found while reviewing
    implementation against donor agreements, regulations, contracts or
    internal procedures — alongside the automated report-scan alerts.
    """

    class Meta:
        model = ComplianceAlert
        fields = ["severity", "requirement_type", "indicator", "report", "message"]
        widgets = {
            "message": forms.Textarea(
                attrs={
                    "rows": 4,
                    "placeholder": (
                        "What was reviewed, which obligation it breaches, and "
                        "the evidence observed."
                    ),
                }
            ),
            "indicator": forms.Select(
                attrs={"data-s2": True, "data-s2-placeholder": "Search indicators…"}
            ),
            "report": forms.Select(
                attrs={"data-s2": True, "data-s2-placeholder": "Search reports…"}
            ),
        }

    def __init__(self, *args, **kwargs):
        super().__init__(*args, **kwargs)
        self.fields["requirement_type"].required = True
        self.fields["indicator"].required = False
        self.fields["report"].required = False
        self.fields["indicator"].help_text = "Optional — link the affected indicator."
        self.fields["report"].help_text = "Optional — link the report reviewed."
        self.fields["report"].queryset = Report.objects.select_related(
            "template"
        ).order_by("-generated_at")
