"""
Resume state management.
Tracks which files have been successfully converted so that
interrupted migrations can be resumed from where they left off.

State is persisted as a JSON file (.migration_state.json) in the output directory.
Each entry records the source file's SHA-256 hash, so re-runs detect
both "already done" and "source changed since last conversion".
"""
import hashlib
import json
import os
from dataclasses import dataclass, field, asdict
from typing import Dict


STATE_FILENAME = ".migration_state.json"


@dataclass
class FileEntry:
    source_hash: str
    source_path: str
    output_path: str
    status: str  # "ok", "error"
    timestamp: str = ""


@dataclass
class MigrationState:
    source_lang: str = ""
    target_lang: str = ""
    files: Dict[str, dict] = field(default_factory=dict)  # rel_path -> FileEntry dict

    def mark_done(self, rel_path: str, entry: FileEntry):
        self.files[rel_path] = asdict(entry)

    def is_done(self, rel_path: str, current_hash: str) -> bool:
        """Return True if the file was already converted and source hasn't changed."""
        entry = self.files.get(rel_path)
        if not entry:
            return False
        return entry.get("status") == "ok" and entry.get("source_hash") == current_hash

    def get_entry(self, rel_path: str) -> dict | None:
        return self.files.get(rel_path)


def file_hash(filepath: str, encoding: str = "utf-8") -> str:
    """Compute SHA-256 of a file's contents."""
    h = hashlib.sha256()
    with open(filepath, "r", encoding=encoding, errors="replace") as f:
        h.update(f.read().encode("utf-8"))
    return h.hexdigest()


def load_state(output_dir: str) -> MigrationState:
    """Load migration state from the output directory, or return empty state."""
    path = os.path.join(output_dir, STATE_FILENAME)
    if not os.path.exists(path):
        return MigrationState()
    try:
        with open(path, "r", encoding="utf-8") as f:
            data = json.load(f)
        state = MigrationState(
            source_lang=data.get("source_lang", ""),
            target_lang=data.get("target_lang", ""),
            files=data.get("files", {}),
        )
        return state
    except (json.JSONDecodeError, KeyError):
        return MigrationState()


def save_state(output_dir: str, state: MigrationState):
    """Persist migration state to the output directory."""
    os.makedirs(output_dir, exist_ok=True)
    path = os.path.join(output_dir, STATE_FILENAME)
    data = {
        "source_lang": state.source_lang,
        "target_lang": state.target_lang,
        "files": state.files,
    }
    with open(path, "w", encoding="utf-8") as f:
        json.dump(data, f, ensure_ascii=False, indent=2)
