from rest_framework.views import APIView
from rest_framework.permissions import IsAuthenticated
from rest_framework.response import Response
from rest_framework import status
from django.shortcuts import get_object_or_404

from drf_spectacular.utils import extend_schema, OpenApiExample

from structures.models import Structure
from .models import CityTaxReportHistory
from .serializers_city_tax_preview import CityTaxPreviewRequestSerializer
from .serializers_city_tax_history import CityTaxReportHistorySerializer
from .views_city_tax_preview import CityTaxPreviewAPIView


MONTH_ABBR = {
    1: "Jan",
    2: "Feb",
    3: "Mar",
    4: "Apr",
    5: "May",
    6: "Jun",
    7: "Jul",
    8: "Aug",
    9: "Sep",
    10: "Oct",
    11: "Nov",
    12: "Dec",
}


def build_period_label(period):
    year = period["year"]
    from_month = period["from_month"]
    to_month = period["to_month"]

    if from_month == to_month:
        return f"{MONTH_ABBR.get(from_month, from_month)} {year}"

    if from_month == 1 and to_month == 12:
        return str(year)

    return f"{MONTH_ABBR.get(from_month, from_month)}-{MONTH_ABBR.get(to_month, to_month)} {year}"


@extend_schema(
    tags=["City Tax"],
    summary="List finalized city tax reports or create a new history entry",
    request=CityTaxPreviewRequestSerializer,
    responses={200: CityTaxReportHistorySerializer(many=True), 201: CityTaxReportHistorySerializer},
    examples=[
        OpenApiExample(
            name="Create History Entry",
            value={
                "period": {"from_month": 1, "to_month": 3, "year": 2026},
                "rates": {"1": 3.0, "2": 3.0, "3": 3.0},
                "property_type_id": 12,
                "property_id": 40,
            },
            request_only=True,
        ),
    ],
)
class CityTaxReportHistoryAPIView(APIView):
    permission_classes = [IsAuthenticated]

    def get(self, request, structure_id):
        structure = get_object_or_404(Structure, id=structure_id)
        reports = CityTaxReportHistory.objects.filter(structure=structure).order_by("-created_at")
        serializer = CityTaxReportHistorySerializer(reports, many=True)
        return Response(serializer.data, status=status.HTTP_200_OK)

    def post(self, request, structure_id):
        structure = get_object_or_404(Structure, id=structure_id)

        payload_serializer = CityTaxPreviewRequestSerializer(data=request.data)
        payload_serializer.is_valid(raise_exception=True)
        validated = payload_serializer.validated_data

        preview_response = CityTaxPreviewAPIView().post(request, structure_id)
        if preview_response.status_code != status.HTTP_200_OK:
            return preview_response

        period = validated["period"]
        rates_payload = {
            str(key): float(value) for key, value in (validated.get("rates") or {}).items()
        }
        label = build_period_label(period)

        entry = CityTaxReportHistory.objects.create(
            structure=structure,
            created_by=request.user,
            status="final",
            period_from_month=period["from_month"],
            period_to_month=period["to_month"],
            period_year=period["year"],
            rates=rates_payload,
            property_type_id=validated.get("property_type_id"),
            property_id=validated.get("property_id"),
            preview_snapshot=dict(preview_response.data),
            label=label,
        )

        serializer = CityTaxReportHistorySerializer(entry)
        return Response(serializer.data, status=status.HTTP_201_CREATED)
