from datetime import date

from django.db import transaction

from rest_framework import status
from rest_framework.response import Response
from rest_framework.views import APIView

from .models import Holiday
from .india_holiday_calendar import (
    get_indian_holidays
)


def import_library_holidays(company, year, location=None):
    """
    Fetch one year of the India holiday library and save it for
    `company` (source="automatic"). Manually added holidays are never
    touched. Returns a small summary dict; raises on fetch failure.
    """

    calendar = get_indian_holidays(year=year, location=location)

    created = 0
    existing = 0

    with transaction.atomic():

        for h in calendar or []:

            holiday, was_created = Holiday.objects.get_or_create(
                company=company,
                date=h["date"],
                name=h["name"],
                defaults={
                    "holiday_type": h["holiday_type"],
                    "description": h.get(
                        "description",
                        f"Automatically imported for {year}.",
                    ),
                    "is_active": True,
                    "source": "automatic",
                },
            )

            if was_created:
                created += 1
            else:
                existing += 1

    return {
        "year": year,
        "fetched": len(calendar or []),
        "created": created,
        "already_exists": existing,
    }


class HolidayCalendarImportView(APIView):

    # =========================================================
    # AUTHENTICATION
    # =========================================================

    def get_authenticators(self):

        from Employee.employee_crud_permissions import (
            AdminOrEmployeeJWTAuthentication,
        )

        return [
            AdminOrEmployeeJWTAuthentication()
        ]

    # =========================================================
    # PERMISSIONS
    # =========================================================

    def get_permissions(self):

        from Employee.employee_crud_permissions import (
            IsAdminOrHR
        )

        return [
            IsAdminOrHR()
        ]

    # =========================================================
    # POST
    # =========================================================

    def post(
        self,
        request,
        *args,
        **kwargs
    ):

        # =====================================================
        # 1. YEAR
        # =====================================================

        try:

            year = int(
                request.data.get(
                    "year",
                    date.today().year
                )
            )

        except (
            TypeError,
            ValueError
        ):

            return Response(
                {
                    "status": "error",
                    "message": (
                        "Year must be a valid number."
                    )
                },
                status=status.HTTP_400_BAD_REQUEST
            )

        # =====================================================
        # 2. VALIDATE YEAR
        # =====================================================

        if year < 1900 or year > 2100:

            return Response(
                {
                    "status": "error",
                    "message": (
                        "Year must be between "
                        "1900 and 2100."
                    )
                },
                status=status.HTTP_400_BAD_REQUEST
            )

        # =====================================================
        # 3. LOCATION
        # =====================================================

        location = request.data.get(
            "location"
        )

        if location:

            location = str(
                location
            ).strip()

            if not location:

                location = None

        # =====================================================
        # 4. GET COMPANY
        # =====================================================

        from Employee.employee_crud_permissions import (
            resolve_company_for_user
        )

        company = resolve_company_for_user(
            request.user
        )

        if company is None:

            return Response(
                {
                    "status": "error",
                    "message": (
                        "Unable to determine "
                        "your company."
                    )
                },
                status=status.HTTP_403_FORBIDDEN
            )

        # =====================================================
        # 4b. MULTI-YEAR IMPORT
        #     {"years": [2025, 2026, 2027]}  or  {"all_years": true}
        #     (all_years = previous, current and next year)
        # =====================================================

        years_raw = request.data.get("years")
        all_years = request.data.get("all_years")

        if years_raw is not None or all_years in (True, "true", "True", 1, "1"):

            if years_raw is None:
                this_year = date.today().year
                years_raw = [this_year - 1, this_year, this_year + 1]

            if not isinstance(years_raw, (list, tuple)):
                years_raw = [years_raw]

            try:
                years = sorted({int(y) for y in years_raw})
            except (TypeError, ValueError):
                return Response(
                    {"status": "error",
                     "message": "years must be a list of valid numbers."},
                    status=status.HTTP_400_BAD_REQUEST
                )

            if not years or len(years) > 10 or any(
                y < 1900 or y > 2100 for y in years
            ):
                return Response(
                    {"status": "error",
                     "message": (
                         "Provide 1 to 10 years, each between "
                         "1900 and 2100."
                     )},
                    status=status.HTTP_400_BAD_REQUEST
                )

            imported = []
            failed = []

            for y in years:
                try:
                    imported.append(
                        import_library_holidays(company, y, location)
                    )
                except Exception as error:
                    failed.append({"year": y, "details": str(error)})

            if not imported:
                return Response(
                    {"status": "error",
                     "message": "Unable to fetch holiday calendar.",
                     "failed_years": failed},
                    status=status.HTTP_503_SERVICE_UNAVAILABLE
                )

            all_company_holidays = list(
                Holiday.objects.filter(company=company, is_active=True)
                .order_by("date")
                .values("id", "name", "date", "holiday_type", "source")
            )

            for item in all_company_holidays:
                item["date"] = str(item["date"])

            return Response(
                {
                    "status": "success",
                    "message": "Holiday calendar imported successfully.",
                    "data": {
                        "location": location or "India",
                        "company_id": company.company_id,
                        "imported_years": imported,
                        "failed_years": failed,
                        "summary": {
                            "automatic_count": sum(
                                1 for h in all_company_holidays
                                if h["source"] == "automatic"
                            ),
                            "manual_count": sum(
                                1 for h in all_company_holidays
                                if h["source"] == "manual"
                            ),
                            "total_holidays_count": len(all_company_holidays),
                        },
                        # library + manual holidays, all years
                        "total_holidays": all_company_holidays,
                    },
                },
                status=status.HTTP_200_OK
            )

        # =====================================================
        # 5. FETCH AUTOMATIC HOLIDAY CALENDAR
        # =====================================================

        try:

            india_calendar = (
                get_indian_holidays(
                    year=year,
                    location=location
                )
            )

        except Exception as error:

            return Response(
                {
                    "status": "error",
                    "message": (
                        "Unable to fetch "
                        "holiday calendar."
                    ),
                    "details": str(error)
                },
                status=(
                    status.HTTP_503_SERVICE_UNAVAILABLE
                )
            )

        # =====================================================
        # 6. CHECK DATA
        # =====================================================

        if not india_calendar:

            return Response(
                {
                    "status": "error",
                    "message": (
                        f"No holiday data was "
                        f"returned for {year}."
                    )
                },
                status=status.HTTP_404_NOT_FOUND
            )

        # =====================================================
        # LISTS
        # =====================================================

        automatic_holidays = []

        newly_created = []

        already_exists = []

        # =====================================================
        # 7. SAVE AUTOMATIC HOLIDAYS
        # =====================================================

        with transaction.atomic():

            for holiday_data in india_calendar:

                holiday_date = (
                    holiday_data["date"]
                )

                holiday_name = (
                    holiday_data["name"]
                )

                holiday_type = (
                    holiday_data["holiday_type"]
                )

                description = (
                    holiday_data.get(
                        "description",
                        f"Automatically imported "
                        f"for {year}."
                    )
                )

                # -------------------------------------------------
                # GET OR CREATE
                # -------------------------------------------------

                holiday, was_created = (
                    Holiday.objects.get_or_create(

                        company=company,

                        date=holiday_date,

                        name=holiday_name,

                        defaults={
                            "holiday_type":
                                holiday_type,

                            "description":
                                description,

                            "is_active":
                                True,

                            "source":
                                "automatic",
                        }
                    )
                )

                # -------------------------------------------------
                # EXISTING RECORD
                # -------------------------------------------------

                if not was_created:

                    update_fields = []

                    # If this holiday came from Calendarific,
                    # make sure it is marked automatic.

                    if holiday.source != "automatic":

                        holiday.source = "automatic"

                        update_fields.append(
                            "source"
                        )

                    # Reactivate if previously inactive.

                    if not holiday.is_active:

                        holiday.is_active = True

                        update_fields.append(
                            "is_active"
                        )

                    if update_fields:

                        holiday.save(
                            update_fields=update_fields
                        )

                # -------------------------------------------------
                # RESPONSE ITEM
                # -------------------------------------------------

                item = {

                    "id":
                        holiday.id,

                    "name":
                        holiday.name,

                    "date":
                        str(
                            holiday.date
                        ),

                    "holiday_type":
                        holiday.holiday_type,

                    "source":
                        "automatic",
                }

                automatic_holidays.append(
                    item
                )

                # -------------------------------------------------
                # CREATED / EXISTING
                # -------------------------------------------------

                if was_created:

                    newly_created.append(
                        item
                    )

                else:

                    already_exists.append(
                        item
                    )

        # =====================================================
        # 8. GET MANUALLY CREATED HOLIDAYS
        # =====================================================

        manual_holidays = list(

            Holiday.objects.filter(

                company=company,

                date__year=year,

                is_active=True,

                source="manual",

            )
            .order_by("date")

            .values(
                "id",
                "name",
                "date",
                "holiday_type",
                "source",
            )
        )

        # =====================================================
        # 9. CONVERT MANUAL DATES
        # =====================================================

        for item in manual_holidays:

            item["date"] = str(
                item["date"]
            )

        # =====================================================
        # 10. ALL COMPANY HOLIDAYS
        # =====================================================

        all_company_holidays = list(

            Holiday.objects.filter(

                company=company,

                date__year=year,

                is_active=True,

            )
            .order_by("date")

            .values(
                "id",
                "name",
                "date",
                "holiday_type",
                "source",
            )
        )

        # =====================================================
        # 11. CONVERT ALL DATES
        # =====================================================

        for item in all_company_holidays:

            item["date"] = str(
                item["date"]
            )

        # =====================================================
        # 12. RESPONSE
        # =====================================================

        return Response(
            {

                "status":
                    "success",

                "response_version":
                    "holiday-import-v8",

                "message":
                    (
                        f"Holiday calendar for "
                        f"{year} imported successfully."
                    ),

                "data": {

                    # -----------------------------------------
                    # BASIC INFORMATION
                    # -----------------------------------------

                    "year":
                        year,

                    "location":
                        location or "India",

                    "company_id":
                        company.company_id,

                    # -----------------------------------------
                    # SUMMARY
                    # -----------------------------------------

                    "summary": {

                        "automatic_holidays_import":
                            len(
                                automatic_holidays
                            ),

                        # "automatic_created_count":
                        #     len(
                        #         newly_created
                        #     ),

                        "automatic_already_exists_count":
                            len(
                                already_exists
                            ),

                        "manual_holidays_count":
                            len(
                                manual_holidays
                            ),

                        "total_holidays_count":
                            len(
                                all_company_holidays
                            ),
                    },

                    # -----------------------------------------
                    # AUTOMATIC HOLIDAYS
                    # -----------------------------------------

                    "calendar_import_list":
                        automatic_holidays,

                    # -----------------------------------------
                    # MANUAL HOLIDAYS
                    # -----------------------------------------

                    "manual_created":
                        manual_holidays,

                    # Total Hoiliday
                    "total_holidays":
                        all_company_holidays,

                    # -----------------------------------------
                    # AUTOMATIC ALREADY EXISTING
                    # -----------------------------------------

                    "already_existing_holidays":
                        already_exists,

                    # -----------------------------------------
                    # OLD RESPONSE FIELDS
                    # -----------------------------------------
                    # These are kept so an existing frontend
                    # does not suddenly break.

                    # "calendar_imported":
                    #     automatic_holidays,

                    # "manual_created":
                    #     manual_holidays,

                    # "total_holidays":
                    #     all_company_holidays,
                }
            },

            status=status.HTTP_200_OK
        )