"""todo-manager 공통 유틸리티.

파일 경로 상수, 로드/저장, ID 생성, 이슈 검색, JSON 출력 헬퍼.
"""

from __future__ import annotations

import json
import os
import re
import shutil
import tempfile
from datetime import datetime
from pathlib import Path
from typing import Any

# 파일 경로
SCRIPT_DIR = Path(__file__).parent
TODO_FILE = SCRIPT_DIR / "todo.json"
BACKUP_FILE = SCRIPT_DIR / "todo.json.bak"
REMOVED_FILE = SCRIPT_DIR / "todo-removed.json"

# 인코딩
ENCODING = "utf-8"


def load_todo() -> dict[str, Any]:
    """todo.json 로드."""
    if not TODO_FILE.exists():
        return {"version": "1.0", "issues": [], "last_synced": None}
    with open(TODO_FILE, encoding=ENCODING) as f:
        return json.load(f)


def save_todo(data: dict[str, Any]) -> None:
    """todo.json 저장 (atomic write + 검증)."""
    # 1. 백업
    if TODO_FILE.exists():
        shutil.copy2(TODO_FILE, BACKUP_FILE)

    # 2. 임시 파일에 쓰기
    fd, tmp_path = tempfile.mkstemp(dir=SCRIPT_DIR, suffix=".tmp")
    try:
        with os.fdopen(fd, "w", encoding=ENCODING) as f:
            json.dump(data, f, ensure_ascii=False, indent=2)

        # 3. JSON 검증 (재파싱)
        with open(tmp_path, encoding=ENCODING) as f:
            json.load(f)  # 검증만

        # 4. atomic rename
        shutil.move(tmp_path, TODO_FILE)

    finally:
        if os.path.exists(tmp_path):
            os.unlink(tmp_path)


def get_next_id(data: dict[str, Any]) -> str:
    """다음 issue ID 생성 (기존 최대 숫자 + 1)."""
    max_num = 0
    for issue in data.get("issues", []):
        match = re.match(r"issue-(\d+)", issue.get("id", ""))
        if match:
            max_num = max(max_num, int(match.group(1)))
    return f"issue-{max_num + 1:03d}"


def find_issue(data: dict[str, Any], issue_id: str) -> dict[str, Any] | None:
    """이슈 찾기."""
    for issue in data.get("issues", []):
        if issue.get("id") == issue_id:
            return issue
    return None


def print_json(data: Any, pretty: bool = True) -> None:
    """JSON 출력."""
    if pretty:
        print(json.dumps(data, ensure_ascii=False, indent=2))
    else:
        print(json.dumps(data, ensure_ascii=False))
