"""Persist in-progress commit messages in the repository COMMIT_EDITMSG file."""

from __future__ import annotations

from pathlib import Path

from pygit2 import Commit, GitError, Repository


def commit_editmsg_path(repo_path: Path) -> Path:
    return repo_path / "COMMIT_EDITMSG"


def _read_draft_text(repo_path: Path) -> str:
    path = commit_editmsg_path(repo_path)
    if not path.is_file():
        return ""
    try:
        text = path.read_text(encoding="utf-8")
    except OSError:
        return ""
    for line in text.splitlines():
        stripped = line.strip()
        if stripped and not stripped.startswith("#"):
            return stripped
    return ""


def load_commit_draft(repo_path: Path, repo: Repository | None = None) -> str:
    draft = _read_draft_text(repo_path)
    if not draft or repo is None:
        return draft
    try:
        head_message = repo.head.peel(Commit).message.strip()
    except GitError:
        return draft
    if draft.strip() == head_message:
        return ""
    return draft


def save_commit_draft(repo_path: Path, message: str) -> None:
    path = commit_editmsg_path(repo_path)
    try:
        if message:
            path.write_text(f"{message}\n", encoding="utf-8")
        elif path.is_file():
            path.unlink()
    except OSError:
        return