"""Read-only HRMS integration API. Register blueprint in app factory.
Set HRMS_INTEGRATION_API_KEY in the server environment before enabling.
"""
import os
import hmac
import calendar
from datetime import date, timedelta, datetime
from flask import Blueprint, request, jsonify, current_app
from models import Employee, Holiday, LeaveRequest, WeekendSettings

integration_bp = Blueprint('integration_api', __name__, url_prefix='/api/v1/integration')

@integration_bp.before_request
def authenticate():
    secret = os.environ.get('HRMS_INTEGRATION_API_KEY', '')
    provided = request.headers.get('X-API-Key', '')
    if not secret:
        return jsonify(success=False, error='Integration API is not configured'), 503
    if not hmac.compare_digest(provided, secret):
        return jsonify(success=False, error='Unauthorized'), 401

def fail(message, status=400):
    return jsonify(success=False, error=message), status

def daily_hours(emp):
    start, end = emp.shift_start, emp.shift_end
    if start and end:
        a = start.hour * 60 + start.minute
        b = end.hour * 60 + end.minute
        return round(((b-a) % 1440) / 60, 2) if a != b else float(current_app.config.get('INTEGRATION_DEFAULT_DAILY_HOURS', 8))
    return float(current_app.config.get('INTEGRATION_DEFAULT_DAILY_HOURS', 8))

def time_string(value):
    return value.strftime('%H:%M') if value else None

def employment_type(emp):
    # The provided Employee model has no employment_type column.
    # Do not fabricate this value. Optionally supply a resolver via app.config.
    resolver = current_app.config.get('INTEGRATION_EMPLOYMENT_TYPE_RESOLVER')
    return resolver(emp) if callable(resolver) else emp.employment_type

def location_id(emp):
    # Employee.location is a string; no location master exists in provided models.
    resolver = current_app.config.get('INTEGRATION_LOCATION_ID_RESOLVER')
    return resolver(emp) if callable(resolver) else None

@integration_bp.get('/employees')
def employees():
    rows = Employee.query.filter(Employee.status.ilike('active')).order_by(Employee.id).all()
    return jsonify(success=True, data=[{
        'employee_id': e.id, 'employee_code': e.employee_code,
        'employee_name': e.full_name, 'email': e.email,
        'department_id': e.department_id,
        'department_name': e.department.name if e.department else None,
        'designation': e.designation.title if e.designation else None,
        'reporting_manager_id': e.reporting_manager_id,
        'location_id': location_id(e), 'location_name': e.location,
        'employment_type': employment_type(e),
        'joining_date': e.date_of_joining.isoformat() if e.date_of_joining else None,
        'last_working_date': e.exit_date.isoformat() if e.exit_date else None,
        'status': (e.status or '').capitalize(),
        'daily_working_hours': daily_hours(e), 'shift_id': None
    } for e in rows])

def inputs():
    raw = request.args.get('employee_ids', '')
    try:
        ids = list(dict.fromkeys(int(s.strip()) for s in raw.split(',')))
        if not ids or len(ids) > 100 or any(x <= 0 for x in ids):
            raise ValueError()
        start = date.fromisoformat(request.args['from_date'])
        end = date.fromisoformat(request.args['to_date'])
        if start > end or (end-start).days > 366:
            raise ValueError()
    except (ValueError, KeyError, TypeError):
        return None, fail('Provide 1-100 employee_ids and valid YYYY-MM-DD from_date/to_date (max 367 days)')
    found = Employee.query.filter(Employee.id.in_(ids), Employee.status.ilike('active')).all()
    by_id = {e.id: e for e in found}
    if len(by_id) != len(ids):
        return None, fail('Unknown or inactive employee IDs: ' + ','.join(str(i) for i in ids if i not in by_id), 404)
    return (ids, by_id, start, end), None

def weekend_factor(day, settings):
    if day.weekday() == 6:
        mode = (settings.sunday if settings else 'working') or 'working'
    elif day.weekday() == 5:
        nth = (day.day - 1) // 7
        mode = getattr(settings, ['first_saturday','second_saturday','third_saturday','fourth_saturday','fifth_saturday'][nth], 'off') if settings else 'working'
    else:
        mode = 'working'
    mode = mode.strip().lower()
    return 0.0 if mode in ('off', 'holiday', 'weekend') else (0.5 if mode in ('half-day', 'half_day', 'half day', 'halfday', 'half') else 1.0)

def calendar_for(emp, start, end, holidays, settings, leaves):
    result = []
    hours = daily_hours(emp)
    for n in range((end-start).days + 1):
        day = start + timedelta(days=n)
        active = (emp.status or '').lower() == 'active' and (not emp.date_of_joining or day >= emp.date_of_joining) and (not emp.exit_date or day <= emp.exit_date)
        fraction = weekend_factor(day, settings) if active else 0
        candidates = [h for h in holidays if h.date == day and (not h.location or (h.location or '').casefold() == (emp.location or '').casefold())]
        # Location-specific holiday takes precedence over global holiday.
        candidates.sort(key=lambda h: bool(h.location), reverse=True)
        holiday = candidates[0] if candidates else None
        optional = bool(holiday and (holiday.type or '').lower() in ('optional', 'rh', 'restricted'))
        public = bool(holiday and not optional)
        if public:
            fraction = 0
        scheduled = round(hours * fraction, 2)
        overlapping = [l for l in leaves if l.start_date and l.end_date and l.start_date <= day <= l.end_date]
        approved = [l for l in overlapping if (l.status or '').lower() in ('final_approved',)]
        # Respect half-day flags and total_days used by the HRMS leave module.
        leave_fraction = min(1.0, sum(0.5 if (l.half_day or float(l.total_days or 0) == 0.5) else 1.0 for l in approved))
        # RH only reduces capacity if it is approved, not merely on the holiday master.
        if optional and any((l.leave_type and l.leave_type.code.upper() == 'RH') for l in approved):
            leave_fraction = min(1.0, max(leave_fraction, 1.0))
        leave_hours = round(min(scheduled, hours * leave_fraction), 2)
        available = round(max(0, scheduled - leave_hours), 2)
        chosen = approved[0] if approved else (overlapping[0] if overlapping else None)
        leave_type = chosen.leave_type.code if chosen and chosen.leave_type else None
        leave_status = ('Approved' if chosen.status == 'final_approved' else 'Pending' if chosen.status in ('pending', 'manager_approved') else (chosen.status or '').capitalize()) if chosen else None
        day_type = 'HOLIDAY' if public else ('WEEKLY_OFF' if fraction == 0 else ('LEAVE' if approved and leave_hours else 'WORKING'))
        result.append(dict(date=day.isoformat(), day_name=day.strftime('%A'), day_type=day_type,
            is_working_day=scheduled > 0, is_weekly_off=active and fraction == 0 and not public,
            is_holiday=public, holiday_name=holiday.name if holiday else None,
            is_optional_holiday=optional, leave_type=leave_type, leave_status=leave_status,
            leave_duration=leave_fraction if approved else 0,
            scheduled_hours=scheduled, leave_hours=leave_hours, available_hours=available,
            shift_start=time_string(emp.shift_start) if scheduled else None,
            shift_end=time_string(emp.shift_end) if scheduled else None))
    return result

def collect(parsed):
    ids, by_id, start, end = parsed
    holidays = Holiday.query.filter(Holiday.date >= start, Holiday.date <= end).all()
    settings = WeekendSettings.query.order_by(WeekendSettings.updated_on.desc()).first()
    leaves = LeaveRequest.query.filter(LeaveRequest.employee_id.in_(ids),
        LeaveRequest.start_date <= end, LeaveRequest.end_date >= start).all()
    by_employee = {i: [] for i in ids}
    for l in leaves:
        by_employee[l.employee_id].append(l)
    return [(i, calendar_for(by_id[i], start, end, holidays, settings, by_employee[i])) for i in ids]

@integration_bp.get('/working-calendar')
def working_calendar():
    parsed, error = inputs()
    if error:
        return error
    return jsonify(success=True, data=[dict(employee_id=i, calendar=days) for i, days in collect(parsed)])

@integration_bp.get('/availability')
def availability():
    parsed, error = inputs()
    if error:
        return error
    ids, by_id, start, end = parsed
    output = []
    for i, days in collect(parsed):
        scheduled = round(sum(d['scheduled_hours'] for d in days), 2)
        leave = round(sum(d['leave_hours'] for d in days), 2)
        standard = daily_hours(by_id[i])
        # Full-day equivalents allow partial Saturdays and half-day leave.
        working = round(scheduled / standard, 2) if standard else 0
        approved_days = round(leave / standard, 2) if standard else 0
        output.append(dict(employee_id=i, calendar_days=len(days), working_days=working,
            weekly_off_days=sum(1 for d in days if d['is_weekly_off']),
            holiday_days=sum(1 for d in days if d['is_holiday']),
            approved_leave_days=approved_days,
            half_day_leave_count=sum(1 for d in days if d['leave_duration'] == 0.5 and d['leave_hours'] > 0),
            available_working_days=round(working-approved_days, 2),
            standard_daily_hours=standard, scheduled_working_hours=scheduled,
            approved_leave_hours=leave, available_working_hours=round(scheduled-leave, 2),
            calendar_status='COMPLETE'))
    return jsonify(success=True, period=dict(from_date=start.isoformat(), to_date=end.isoformat()), data=output)
