"""
批次作業基礎工具
提供 log_batch_execution 等共用函式
"""
import logging
from datetime import datetime
from typing import Optional

logger = logging.getLogger(__name__)


def log_batch_execution(
    batch_name: str,
    status: str,
    message: Optional[str] = None,
    started_at: Optional[datetime] = None,
    finished_at: Optional[datetime] = None,
) -> None:
    """
    記錄批次執行日誌到資料庫

    Args:
        batch_name: 批次名稱
        status: 執行狀態 (success/failed/warning)
        message: 執行訊息
        started_at: 開始時間 (若未提供則使用 finished_at)
        finished_at: 完成時間 (若未提供則使用現在)
    """
    from app.db.session import get_db
    from app.models.batch_log import BatchLog

    now = datetime.utcnow()
    finished = finished_at or now
    started = started_at or finished

    duration = None
    if started and finished:
        duration = int((finished - started).total_seconds())

    try:
        db = next(get_db())
        log_entry = BatchLog(
            batch_name=batch_name,
            status=status,
            message=message,
            started_at=started,
            finished_at=finished,
            duration_seconds=duration,
        )
        db.add(log_entry)
        db.commit()
        logger.info(f"[{batch_name}] 批次執行記錄已寫入: {status}")
    except Exception as e:
        logger.error(f"[{batch_name}] 寫入批次日誌失敗: {e}")
    finally:
        try:
            db.close()
        except Exception:
            pass
