import hashlib
import json
from pathlib import Path
from typing import List, Optional, Set

CACHE_DIR = '.leaf-publisher-cache'
CACHE_FILE = 'deps_cache.json'


def get_files_hash(project_dir: Path, ignore_dirs: Set[str]) -> str:
    """计算所有 .py 文件的 mtime 哈希"""
    hasher = hashlib.sha256()
    for py_file in sorted(project_dir.rglob('*.py')):
        if any(part in ignore_dirs for part in py_file.parts):
            continue
        mtime = str(py_file.stat().st_mtime)
        hasher.update(mtime.encode())
    return hasher.hexdigest()


def load_deps_cache(project_dir: Path, ignore_dirs: Set[str]) -> Optional[List[str]]:
    cache_dir = project_dir / CACHE_DIR
    cache_file = cache_dir / CACHE_FILE
    if not cache_file.exists():
        return None
    try:
        with open(cache_file, 'r', encoding='utf-8') as f:
            data = json.load(f)
        current_hash = get_files_hash(project_dir, ignore_dirs)
        if data.get('files_hash') == current_hash:
            return data.get('dependencies', [])
    except (json.JSONDecodeError, OSError):
        pass
    return None


def save_deps_cache(project_dir: Path, dependencies: List[str], ignore_dirs: Set[str]) -> None:
    cache_dir = project_dir / CACHE_DIR
    cache_dir.mkdir(exist_ok=True)
    cache_file = cache_dir / CACHE_FILE
    current_hash = get_files_hash(project_dir, ignore_dirs)
    data = {
        'files_hash': current_hash,
        'dependencies': dependencies
    }
    with open(cache_file, 'w', encoding='utf-8') as f:
        json.dump(data, f, indent=2)