from datetime import timedelta
from models import Attendance


def sync_leave_to_attendance(
    db,
    employee_id: int,
    start_date,
    end_date,
    leave_type_name: str,
    half_day: bool = False,
    half_day_session: str = "FH",   # "FH" or "SH"
):
    """
    Sync approved leave into Attendance.

    Rules:
    - Holiday/Weekend rows are never overwritten.
    - Full-day leave: marks the day as Leave in Attendance (safe overwrite).
    - Half-day leave: ONLY tags Attendance.note with HD_LEAVE:FH/SH and LT:<leave>,
      but DOES NOT overwrite attendance remarks/status/source/check-in/out/hours.
      This allows the other half to be derived from biometric/self/desktime engine.
    """

    half_day_session = (half_day_session or "FH").strip().upper()
    if half_day_session not in ("FH", "SH"):
        half_day_session = "FH"

    # normalize leave label
    leave_label = (leave_type_name or "Leave").strip()

    curr_date = start_date
    while curr_date <= end_date:
        attn = Attendance.query.filter_by(employee_id=employee_id, date=curr_date).first()
        if not attn:
            attn = Attendance(employee_id=employee_id, date=curr_date)
            db.session.add(attn)

        # Do not overwrite Holiday/Weekend
        existing_remark = (getattr(attn, "remarks", None) or "").strip()
        if existing_remark in ("Holiday", "Weekend"):
            curr_date += timedelta(days=1)
            continue

        if half_day:
            # Half-day: tag only (do NOT override computed attendance)
            if hasattr(attn, "note"):
                base = (attn.note or "").strip()

                tag_hd = f"HD_LEAVE:{half_day_session}"
                tag_lt = f"LT:{leave_label}"

                # split by "|" and clean
                parts = [p.strip() for p in base.split("|") if p.strip()] if base else []

                # remove any existing HD_LEAVE tag (so updates don't duplicate)
                parts = [p for p in parts if not p.startswith("HD_LEAVE:")]

                # remove any existing LT tag (optional, keeps only latest)
                parts = [p for p in parts if not p.startswith("LT:")]

                parts.extend([tag_hd, tag_lt])

                attn.note = " | ".join(parts)

            # IMPORTANT: we intentionally do NOT set:
            # attn.remarks, attn.status, attn.source, attn.check_in_time, attn.check_out_time, attn.working_hours

        else:
            # Full-day leave: apply Leave status
            if hasattr(attn, "status"):
                attn.status = "Leave"

            # Keep remarks consistent with your other parts of the system
            # (your monthly summary expects remarks like 'Leave', 'Present', etc.)
            attn.remarks = "Leave"

            if hasattr(attn, "source"):
                attn.source = "Leave"

            if hasattr(attn, "note"):
                # preserve non-leave notes if you want; this overwrites.
                attn.note = f"LT:{leave_label}"

        curr_date += timedelta(days=1)

    # do not commit here; caller should commit