
import logging
from datetime import datetime, timedelta

from django.db import transaction, IntegrityError
from django.http import JsonResponse
from django.utils import timezone

from NexusApp.models.attendance_model import AttendanceMaster
from NexusApp.models.checkin_model import StaffCheckIn


logger = logging.getLogger(__name__)


def _location(request):
    """
    Read latitude / longitude / accuracy sent by the browser.
    Returns (dict of model values, error message or None).
    When the browser could not get a location it sends location_error instead.
    """
    from decimal import Decimal, InvalidOperation
    lat = request.POST.get('latitude', '').strip()
    lng = request.POST.get('longitude', '').strip()
    acc = request.POST.get('accuracy', '').strip()
    note = request.POST.get('location_error', '').strip()[:120]

    if not lat and not lng:
        if not note:
            return None, 'Location is required. Allow location access and try again.'
        return {'latitude': None, 'longitude': None, 'accuracy': None,
                'note': 'Not captured: ' + note[:100]}, None
    try:
        lat_d, lng_d = Decimal(lat), Decimal(lng)
    except InvalidOperation:
        return None, 'Invalid location received.'
    if not (-90 <= lat_d <= 90 and -180 <= lng_d <= 180):
        return None, 'Invalid location received.'
    try:
        accuracy = max(int(float(acc)), 0) if acc else None
    except ValueError:
        accuracy = None
    return {'latitude': lat_d.quantize(Decimal('0.000001')),
            'longitude': lng_d.quantize(Decimal('0.000001')),
            'accuracy': accuracy, 'note': ''}, None


def staff_checkin(request):

    # -----------------------------------------
    # 1. REQUEST METHOD VALIDATION
    # -----------------------------------------

    if request.method != 'POST':

        logger.warning(
            "Staff check-in rejected: Invalid request method. Method=%s",
            request.method
        )

        return JsonResponse({
            'success': False,
            'message': 'Invalid request method.'
        }, status=405)


    # -----------------------------------------
    # 2. STAFF AUTHENTICATION VALIDATION
    # -----------------------------------------

    staff = getattr(request, 'staff', None)

    if not staff:

        logger.warning(
            "Staff check-in rejected: Staff authentication missing."
        )

        return JsonResponse({
            'success': False,
            'message': 'Staff authentication required.'
        }, status=401)

    staff_id = staff.pk


    # -----------------------------------------
    # 3. ATTENDANCE SETTINGS VALIDATION
    # -----------------------------------------

    try:

        master = AttendanceMaster.objects.filter(
            is_active=True
        ).first()

        if not master:

            logger.error(
                "Staff check-in failed: No active AttendanceMaster. Staff ID=%s",
                staff_id
            )

            return JsonResponse({
                'success': False,
                'message': 'Attendance settings are not configured. Please contact admin.'
            }, status=400)


        if master.start_time is None:

            logger.error(
                "Staff check-in failed: Attendance start time missing. Staff ID=%s",
                staff_id
            )

            return JsonResponse({
                'success': False,
                'message': 'Attendance start time is not configured.'
            }, status=400)


        grace_minutes = master.late_grace_minutes

        if grace_minutes is None or grace_minutes < 0:

            logger.error(
                "Invalid attendance grace minutes. Staff ID=%s, Value=%s",
                staff_id,
                grace_minutes
            )

            return JsonResponse({
                'success': False,
                'message': 'Invalid attendance grace time configuration.'
            }, status=400)


    except Exception:

        logger.exception(
            "Database error while loading attendance settings. Staff ID=%s",
            staff_id
        )

        return JsonResponse({
            'success': False,
            'message': 'Unable to load attendance settings. Please try again.'
        }, status=500)


    # -----------------------------------------
    # 4. CURRENT DATE AND TIME
    # -----------------------------------------

    now = timezone.now()

    local_now = timezone.localtime(now)

    today = local_now.date()


    # -----------------------------------------
    # 5. CALCULATE LATE STATUS
    # -----------------------------------------

    shift_start = datetime.combine(
        today,
        master.start_time
    )

    shift_start = timezone.make_aware(
        shift_start,
        timezone.get_current_timezone()
    )

    grace_end = shift_start + timedelta(
        minutes=grace_minutes
    )

    is_late = local_now > grace_end

    late_minutes = 0

    if is_late:

        late_minutes = max(
            1,
            int(
                (local_now - grace_end).total_seconds() // 60
            )
        )


    # -----------------------------------------
    # 6. LATE REASON VALIDATION
    # -----------------------------------------

    late_reason = request.POST.get(
        'late_reason',
        ''
    ).strip()


    if is_late and not late_reason:

        logger.warning(
            "Staff check-in rejected: Late reason missing. Staff ID=%s, Date=%s",
            staff_id,
            today
        )

        return JsonResponse({
            'success': False,
            'needs_reason': True,
            'message': 'Please enter the reason for your late check-in.'
        }, status=422)


    if is_late and len(late_reason) < 5:
       return JsonResponse({
        'success': False,
        'message': 'Late reason must contain at least 5 characters.'
    }, status=422)

    if is_late and len(late_reason) > 50:
        return JsonResponse({
            'success': False,
            'message': 'Late reason cannot exceed 50 characters.'
        }, status=422)

    location, loc_error = _location(request)
    if loc_error:
        return JsonResponse({'success': False, 'message': loc_error}, status=422)

    # -----------------------------------------
    # 7. SAVE CHECK-IN USING TRANSACTION
    # -----------------------------------------

    try:

        with transaction.atomic():

            attendance, created = StaffCheckIn.objects.get_or_create(

                staff=staff,

                check_in_date=today,

                defaults={

                    'check_in_time': now,

                    'status': 'late' if is_late else 'on_time',

                    'late_reason': late_reason if is_late else '',

                    'late_minutes': late_minutes,

                    'check_in_latitude': location['latitude'],
                    'check_in_longitude': location['longitude'],
                    'check_in_accuracy': location['accuracy'],
                    'check_in_location_note': location['note'],

                }
            )


            # ---------------------------------
            # 8. DUPLICATE CHECK-IN VALIDATION
            # ---------------------------------

            if not created:

                logger.warning(
                    "Duplicate staff check-in rejected. Staff ID=%s, Date=%s",
                    staff_id,
                    today
                )

                return JsonResponse({
                    'success': False,
                    'message': 'You have already checked in today.'
                }, status=409)


        # -------------------------------------
        # 9. SUCCESS LOGGING
        # -------------------------------------

        logger.info(
            "Staff check-in successful. "
            "Staff ID=%s, Attendance ID=%s, Date=%s, "
            "Status=%s, Late Minutes=%s",
            staff_id,
            attendance.pk,
            today,
            attendance.status,
            late_minutes
        )


        # -------------------------------------
        # 10. SUCCESS RESPONSE
        # -------------------------------------

        return JsonResponse({

            'success': True,

            'message': (
                'Late check-in recorded successfully.'
                if is_late
                else 'Check-in successful!'
            ),

            'check_in_time': local_now.strftime('%I:%M:%S %p'),

            'is_late': is_late,

            'late_minutes': late_minutes

        }, status=201)


    # -----------------------------------------
    # 11. DATABASE INTEGRITY ERROR
    # -----------------------------------------

    except IntegrityError:

        logger.exception(
            "Database integrity error during staff check-in. Staff ID=%s, Date=%s",
            staff_id,
            today
        )

        return JsonResponse({
            'success': False,
            'message': 'You have already checked in today or a database constraint was violated.'
        }, status=409)


    # -----------------------------------------
    # 12. UNEXPECTED ERROR
    # -----------------------------------------

    except Exception:

        logger.exception(
            "Unexpected error during staff check-in. Staff ID=%s, Date=%s",
            staff_id,
            today
        )

        return JsonResponse({
            'success': False,
            'message': 'Unable to check in. Please try again.'
        }, status=500)



def staff_checkout(request):
    """Check out for today: needs today's check-in, stores location and working hours."""
    if request.method != 'POST':
        return JsonResponse({'success': False, 'message': 'Invalid request method.'}, status=405)
    staff = getattr(request, 'staff', None)
    if not staff:
        return JsonResponse({'success': False, 'message': 'Staff authentication required.'}, status=401)

    location, loc_error = _location(request)
    if loc_error:
        return JsonResponse({'success': False, 'message': loc_error}, status=422)

    now = timezone.now()
    today = timezone.localtime(now).date()
    try:
        with transaction.atomic():
            attendance = StaffCheckIn.objects.select_for_update().filter(
                staff=staff, check_in_date=today).first()
            if attendance is None:
                return JsonResponse({'success': False,
                                     'message': 'You have not checked in today. Check in first.'},
                                    status=409)
            if attendance.check_out_time:
                return JsonResponse({'success': False,
                                     'message': 'You have already checked out today.'}, status=409)

            minutes = max(int((now - attendance.check_in_time).total_seconds() // 60), 0)
            attendance.check_out_time = now
            attendance.check_out_latitude = location['latitude']
            attendance.check_out_longitude = location['longitude']
            attendance.check_out_accuracy = location['accuracy']
            attendance.check_out_location_note = location['note']
            attendance.working_minutes = minutes
            attendance.save()
    except Exception:
        logger.exception('Staff check-out failed. Staff ID=%s', staff.pk)
        return JsonResponse({'success': False, 'message': 'Unable to check out. Please try again.'},
                            status=500)

    logger.info('Staff check-out. Staff ID=%s, minutes=%s', staff.pk, minutes)
    return JsonResponse({
        'success': True,
        'message': f'Checked out. You worked {attendance.working_hours_label} today.',
        'check_out_time': timezone.localtime(now).strftime('%I:%M %p'),
        'working_hours': attendance.working_hours_label,
    })
