"""Parser and exporter functions for shogi game records."""

from pathlib import Path

from rshogi._rshogi import (
    export_csa as _export_csa,
    export_jkf as _export_jkf,
    export_ki2 as _export_ki2,
    export_kif as _export_kif,
    parse_csa_str,
    parse_kif_str,
)


def _default_kif_encoding(path: Path) -> str:
    suffix = path.suffix.lower()
    if suffix == ".kifu":
        return "utf-8"
    return "shift_jis"


def _default_ki2_encoding(path: Path) -> str:
    suffix = path.suffix.lower()
    if suffix == ".ki2":
        return "shift_jis"
    return "shift_jis"


def read_kif(path: str | Path, *, encoding: str | None = None):
    """Read a KIF file and return GameRecord."""
    path = Path(path)
    if encoding is None:
        encoding = _default_kif_encoding(path)
    text = path.read_text(encoding=encoding)
    return parse_kif_str(text)


def read_csa(path: str | Path, *, encoding: str | None = "shift_jis"):
    """Read a CSA file and return GameRecord."""
    text = Path(path).read_text(encoding=encoding)
    return parse_csa_str(text)


def export_kif_str(record):
    """Export GameRecord to KIF string."""
    return _export_kif(record)


def export_csa_str(record):
    """Export GameRecord to CSA string."""
    return _export_csa(record)


def export_ki2_str(record):
    """Export GameRecord to KI2 string."""
    return _export_ki2(record)


def export_jkf_str(record):
    """Export GameRecord to JKF string."""
    return _export_jkf(record)


def write_kif(path: str | Path, record, *, encoding: str | None = None) -> None:
    """Write GameRecord as KIF file."""
    path = Path(path)
    if encoding is None:
        encoding = _default_kif_encoding(path)
    text = export_kif_str(record)
    path.write_text(text, encoding=encoding)


def write_csa(path: str | Path, record, *, encoding: str | None = "shift_jis") -> None:
    """Write GameRecord as CSA file."""
    text = export_csa_str(record)
    Path(path).write_text(text, encoding=encoding)


def write_ki2(path: str | Path, record, *, encoding: str | None = None) -> None:
    """Write GameRecord as KI2 file."""
    path = Path(path)
    if encoding is None:
        encoding = _default_ki2_encoding(path)
    text = export_ki2_str(record)
    path.write_text(text, encoding=encoding)


def write_jkf(path: str | Path, record, *, encoding: str | None = "utf-8") -> None:
    """Write GameRecord as JKF file."""
    text = export_jkf_str(record)
    Path(path).write_text(text, encoding=encoding)

__all__ = [
    "read_kif",
    "read_csa",
    "parse_kif_str",
    "parse_csa_str",
    "export_kif_str",
    "export_ki2_str",
    "export_csa_str",
    "export_jkf_str",
    "write_kif",
    "write_ki2",
    "write_csa",
    "write_jkf",
]
