import logging
import math
from datetime import datetime, time, timedelta
from sqlalchemy.exc import IntegrityError
from app.extensions import db
from app.core.models import Status, Settings
from app.modules.hris.models import Attendance, EmployeeSchedule, Shift, Holiday

def calculate_distance(lat1, lon1, lat2, lon2):
    """
    Calculate distance between two points in meters using Haversine formula.
    """
    if None in (lat1, lon1, lat2, lon2):
        return float('inf')
        
    R = 6371000  # radius of Earth in meters
    phi1 = math.radians(float(lat1))
    phi2 = math.radians(float(lat2))
    delta_phi = math.radians(float(lat2) - float(lat1))
    delta_lambda = math.radians(float(lon2) - float(lon1))

    a = math.sin(delta_phi / 2.0) ** 2 + \
        math.cos(phi1) * math.cos(phi2) * \
        math.sin(delta_lambda / 2.0) ** 2
    
    c = 2 * math.atan2(math.sqrt(a), math.sqrt(1 - a))
    return R * c

class AttendanceService:
    """
    Handles Attendance Logic: Check-in/out, Status Calculation (Late, Overtime, Undertime).
    """

    @staticmethod
    def get_todays_schedule(employee_id, date_obj):
        """
        Retrieves the shift for a specific date.
        Fallback to default 9-17 if no schedule found.
        """
        schedule = EmployeeSchedule.query.filter_by(employee_id=employee_id, date=date_obj).first()
        if schedule:
            return schedule.shift

        # Default Fallback
        # In production, maybe return None and raise error "No Shift Assigned"
        # For prototype, assume 09:00 - 17:00
        return Shift(name="Default", start_time=time(9,0), end_time=time(17,0))

    @staticmethod
    def process_check_in(employee, lat=None, lng=None, photo_path=None, late_reason=None, late_attachment=None):
        """
        Process Check-In logic.
        """
        today = datetime.now().date()
        now = datetime.now()

        # 1. Validation: Already checked in?
        existing = Attendance.query.filter_by(employee_id=employee.id, date=today).first()
        if existing:
            return False, "Already checked in today."
            
        # 1.5. Geofence Validation
        if not employee.is_remote_allowed:
            if not lat or not lng:
                return False, "Location required. Please enable location services."
                
            from app.core.models.office import Office
            office = getattr(employee, 'office', None)
            # If no office is loaded in the relationship yet, fetch it
            if not office and employee.office_id:
                office = Office.query.get(employee.office_id)
                
            if office and office.latitude and office.longitude:
                dist = calculate_distance(lat, lng, office.latitude, office.longitude)
                radius = office.radius_meters or 100
                if dist > radius:
                    return False, f"Anda berada di luar area absen kantor ({int(dist)}m > {radius}m)."
            elif not office:
                # If they must be at office but have no office assigned, we might reject or allow.
                # Usually we want to force assigning an office first.
                return False, "Silakan hubungi HR untuk menentukan lokasi Kantor (Office) Anda terlebih dahulu."

        # 2. Get Shift
        shift = AttendanceService.get_todays_schedule(employee.id, today)

        # 3. Calculate Status (Late vs On Time)
        tolerance_setting = Settings.query.filter_by(key='tolerance_late_minutes').first()
        tolerance = int(tolerance_setting.value) if tolerance_setting else 15

        shift_start_dt = datetime.combine(today, shift.start_time)

        status_slug = 'attn_onwork'
        if now > (shift_start_dt + timedelta(minutes=tolerance)):
            # If late, must provide reason
            if not late_reason or str(late_reason).strip() == "":
                return False, "Alasan terlambat (late_reason) wajib diisi jika check-in melebihi batas waktu."
            
            status_slug = 'attn_late'
        else:
            status_slug = 'attn_onwork'
            # If on time, ignore late reason
            late_reason = None
            late_attachment = None

        status = Status.query.filter_by(slug=status_slug).first()
        if not status:
             # Seed might be missing 'attn_onwork', fallback
             status = Status.query.filter_by(module='hris', system_tag='PROCESS').first()

        attendance = Attendance(
            employee_id=employee.id,
            date=today,
            check_in=now,
            status_id=status.id,
            location_lat=str(lat) if lat else None,
            location_long=str(lng) if lng else None,
            photo_url=photo_path,
            late_reason=late_reason,
            late_attachment=late_attachment
        )
        db.session.add(attendance)
        try:
            db.session.commit()
        except IntegrityError:
            db.session.rollback()
            return False, "Already checked in today."

        return True, "Checked in successfully."

    @staticmethod
    def process_check_out(employee):
        """
        Process Check-Out logic.
        """
        today = datetime.now().date()
        now = datetime.now()

        attendance = Attendance.query.filter_by(employee_id=employee.id, date=today).first()
        if not attendance:
            return False, "No check-in record found for today."

        if attendance.check_out:
            return False, "Already checked out."

        attendance.check_out = now

        # Calculate Final Status (Overtime/Undertime/Normal)
        shift = AttendanceService.get_todays_schedule(employee.id, today)
        shift_end_dt = datetime.combine(today, shift.end_time)

        tolerance_setting = Settings.query.filter_by(key='tolerance_late_minutes').first()
        tolerance = int(tolerance_setting.value) if tolerance_setting else 15

        # Check Undertime (Left early)
        if now < (shift_end_dt - timedelta(minutes=tolerance)):
            status_slug = 'attn_undertime'
        # Check Overtime (Stayed late)
        elif now > (shift_end_dt + timedelta(minutes=tolerance)):
            status_slug = 'attn_overtime'
        else:
            # Normal exit.
            # If check-in was late, keep 'attn_late'?
            # If check-in was normal, set 'attn_present' (On Time & Full Day).
            # This logic can be complex. Let's prioritize the "worst" flag.
            current_status = attendance.status
            if current_status.slug == 'attn_late':
                status_slug = 'attn_late' # Keep late status
            else:
                status_slug = 'attn_present'

        status = Status.query.filter_by(slug=status_slug).first()
        if status:
            attendance.status_id = status.id

        db.session.commit()
        return True, f"Checked out. Status: {status.name if status else 'Unknown'}"
