#!/usr/bin/env python3
"""
에러 알림 모듈

최근 에러 개수를 모니터링하고 임계값을 초과할 때 알림을 전송합니다.
"""

import json
import subprocess
from datetime import datetime, timedelta
from pathlib import Path
from typing import Any, Dict, List

# 에러 기록 파일 경로 (실제 값으로 변경 가능)
ERRORS_FILE = "/tmp/errors.jsonl"


def check_error_threshold(minutes: int = 30, max_errors: int = 5) -> bool:
    """
    최근 minutes분 이내 에러 개수가 max_errors를 초과하면 True 반환.

    Args:
        minutes: 확인할 시간 범위 (분 단위)
        max_errors: 에러 개수 임계값

    Returns:
        에러 개수 > max_errors이면 True, 아니면 False
    """
    try:
        errors = get_recent_errors_in_window(minutes)
        return len(errors) > max_errors
    except (FileNotFoundError, json.JSONDecodeError, Exception):
        return False


def get_recent_errors_in_window(minutes: int = 30) -> List[Dict[str, Any]]:
    """
    최근 minutes분 이내 에러 목록 반환.

    Args:
        minutes: 확인할 시간 범위 (분 단위)

    Returns:
        에러 레코드 리스트
    """
    if not Path(ERRORS_FILE).exists():
        return []

    errors = []
    cutoff_time = datetime.now() - timedelta(minutes=minutes)

    try:
        with open(ERRORS_FILE, "r") as f:
            for line in f:
                if not line.strip():
                    continue
                record = json.loads(line)
                error_time = datetime.fromisoformat(record.get("ts", ""))
                if error_time >= cutoff_time:
                    errors.append(record)
    except (json.JSONDecodeError, ValueError, Exception):
        pass

    return errors


def format_alert_message(errors: List[Dict[str, Any]]) -> str:
    """
    에러 요약 메시지 생성.

    Args:
        errors: 에러 레코드 리스트

    Returns:
        포맷된 알림 메시지
    """
    if not errors:
        return "[에러 알림] 에러가 없습니다."

    message = f"[에러 알림] {len(errors)}건의 에러 발생\n"

    # 최대 3건만 표시
    display_count = min(3, len(errors))
    for i in range(display_count):
        error = errors[i]
        error_type = error.get("error_type", "Unknown")
        msg = error.get("message", "")
        message += f"  - {error_type}: {msg}\n"

    # 초과 에러 개수 표시
    if len(errors) > 3:
        extra_count = len(errors) - 3
        message += f"  외 {extra_count}건\n"

    return message.rstrip()


def send_alert(message: str) -> bool:
    """
    알림 메시지를 cokacdir로 전송.

    Args:
        message: 전송할 메시지

    Returns:
        성공하면 True, 실패하면 False
    """
    try:
        result = subprocess.run(["cokacdir", message], capture_output=True, timeout=5)
        return result.returncode == 0
    except Exception:
        return False
