"""
화면 잠금 감지 컨트롤러.

- AUTO_BREAK_ON_LOCK: 출근 후 잠금→외출, 해제→복귀
- CLOCK_IN_ON_UNLOCK: 미출근 상태에서 잠금 해제 시 출근 자동 기록
"""
from __future__ import annotations
from datetime import datetime

from core.settings_keys import AUTO_BREAK_ON_LOCK, CLOCK_IN_ON_UNLOCK
import sqlite3


class LockMonitor:
    """MainWindow에서 5초마다 호출되는 잠금 상태 감시자."""

    def __init__(self, window):
        self.window = window
        self.db = window.db
        self.last_locked: bool = False
        self._detector_failed_once: bool = False  # 첫 실패만 로깅 (5초 폴링 노이즈 방지)

    def tick(self) -> None:
        try:
            from utils.lock_detector import is_screen_locked
            locked = is_screen_locked()
        except Exception as e:
            if not self._detector_failed_once:
                self._detector_failed_once = True
                from utils.debug_log import dlog
                dlog(f"lock detector failed (silenced after first): {e}")
            return

        was_locked = self.last_locked
        self.last_locked = locked

        # 출근 후 자동 외출/복귀
        if (self.db.get_setting(AUTO_BREAK_ON_LOCK, 'false').lower() == 'true'
                and self.window.is_clocked_in):
            if locked and not was_locked and not self.window.is_on_break:
                self.window.break_out(silent=True)
            elif not locked and was_locked and self.window.is_on_break:
                self.window.break_in(silent=True)

        # 미출근 상태에서 잠금 해제 시 출근
        if (not locked and was_locked
                and not self.window.is_clocked_in
                and self.db.get_setting(CLOCK_IN_ON_UNLOCK, 'false').lower() == 'true'):
            now = datetime.now()
            today_record = self.db.get_today_record()
            if not today_record or not today_record.get('clock_in'):
                self._auto_clock_in_at(now)

    def _auto_clock_in_at(self, when: datetime) -> None:
        w = self.window
        w.clock_in_time = when
        w.is_clocked_in = True
        w.midnight_rollover_handled = False
        w.auto_lunch_applied_today = False

        today = when.date().isoformat()
        clock_in_str = when.strftime("%H:%M:%S")
        existing = self.db.get_today_record()
        if existing:
            with self.db._conn() as conn:
                cursor = conn.cursor()
                cursor.execute(
                    "UPDATE work_records SET clock_in = ?, is_manual = 0 WHERE date = ?",
                    (clock_in_str, today),
                )
                conn.commit()
        else:
            try:
                self.db.add_work_record(today, clock_in_str)
            except sqlite3.IntegrityError:
                # get_today_record()와 add_work_record() 사이 경쟁 조건
                with self.db._conn() as conn:
                    cursor = conn.cursor()
                    cursor.execute(
                        "UPDATE work_records SET clock_in = ?, is_manual = 0 WHERE date = ?",
                        (clock_in_str, today),
                    )
                    conn.commit()
        w.update_display()
