from __future__ import annotations

import os
from pathlib import Path


def _candidate_paths() -> tuple[list[Path], list[Path]]:
    root = Path(__file__).resolve().parents[2]
    fonts_dir = root / "assets" / "fonts"
    explicit_regular_path = os.getenv("RECEIPT_FONT_PATH")
    explicit_bold_path = os.getenv("RECEIPT_FONT_BOLD_PATH")

    regular_candidates = []
    if explicit_regular_path:
        regular_candidates.append(Path(explicit_regular_path).expanduser())

    regular_candidates.extend([
        fonts_dir / "NotoSerifGujarati-Regular.ttf",
        fonts_dir / "NotoSerifGujarati-Medium.ttf",
        fonts_dir / "NotoSansGujarati-Regular.ttf",
        fonts_dir / "AnekGujarati-Regular.ttf",
        fonts_dir / "AnekGujarati-Medium.ttf",
    ])

    bold_candidates = []
    if explicit_bold_path:
        bold_candidates.append(Path(explicit_bold_path).expanduser())
    if explicit_regular_path:
        bold_candidates.append(Path(explicit_regular_path).expanduser())

    bold_candidates.extend([
        fonts_dir / "NotoSerifGujarati-Bold.ttf",
        fonts_dir / "NotoSerifGujarati-Medium.ttf",
        fonts_dir / "NotoSansGujarati-SemiBold.ttf",
        fonts_dir / "NotoSansGujarati-Regular.ttf",
        fonts_dir / "AnekGujarati-Medium.ttf",
        fonts_dir / "AnekGujarati-Regular.ttf",
    ])

    return regular_candidates, bold_candidates


def _resolve_font(candidates: list[Path]) -> Path | None:
    for candidate in candidates:
        if candidate.exists() and candidate.is_file():
            return candidate
    return None


def resolve_gujarati_font_paths() -> tuple[Path, Path]:
    regular_candidates, bold_candidates = _candidate_paths()
    regular_path = _resolve_font(regular_candidates)

    if not regular_path:
        raise RuntimeError(
            "Required Gujarati font file not found. Set RECEIPT_FONT_PATH/RECEIPT_FONT_BOLD_PATH or provide a supported font under assets/fonts such as NotoSerifGujarati-Regular.ttf."
        )

    bold_path = _resolve_font(bold_candidates) or regular_path
    return regular_path, bold_path
