"""백그라운드 태스크 레지스트리 — 활성 태스크 추적 + 시작 시 stale 복구."""
import logging
import threading
from typing import Dict, Optional

logger = logging.getLogger(__name__)

_active_tasks: Dict[str, threading.Thread] = {}
_lock = threading.Lock()


def register_task(task_key: str, thread: threading.Thread) -> bool:
    """태스크 등록. 이미 실행 중이면 False 반환."""
    with _lock:
        existing = _active_tasks.get(task_key)
        if existing and existing.is_alive():
            return False
        _active_tasks[task_key] = thread
        return True


def unregister_task(task_key: str) -> None:
    with _lock:
        _active_tasks.pop(task_key, None)


def is_task_running(task_key: str) -> bool:
    with _lock:
        t = _active_tasks.get(task_key)
        return t is not None and t.is_alive()


def recover_stale_progress(db_session) -> int:
    """시작 시 running 상태로 남은 PipelineProgress를 error로 복구."""
    from app.models.project import PipelineProgress
    count = db_session.query(PipelineProgress).filter(
        PipelineProgress.status == "running"
    ).update({"status": "error", "error_message": "Server restarted during operation"})
    db_session.commit()
    return count
