from __future__ import annotations

import json
from pathlib import Path
import re

from ..utils.record_tools import payload_to_records

TUID_DIR_PREFIX_PATTERN = re.compile(
    r"^(?P<tuid>\d{8}-\d{6}-\d{3}-[A-Za-z0-9]{6})(?:-|$)"
)


def load_json_file_records(path: str | Path) -> list[dict[str, object]]:
    """Load one JSON file and normalize it into standard record dictionaries.

    Parameters
    ----------
    path : str | Path
        Path to a JSON file.

    Returns
    -------
    list[dict[str, object]]
        Normalized records.

    Raises
    ------
    ValueError
        If JSON payload cannot be normalized into records.
    json.JSONDecodeError
        If file content is not valid JSON.
    """
    file_path = Path(path).expanduser()
    payload = json.loads(file_path.read_text(encoding="utf-8"))
    records = payload_to_records(payload)

    if file_path.name.startswith("quantities_of_interest"):
        inferred_tuid = _infer_tuid_from_path(file_path)
        if inferred_tuid is not None:
            for record in records:
                tuid = record.get("tuid")
                if not (isinstance(tuid, str) and tuid.strip()):
                    record["tuid"] = inferred_tuid

    return records


def _infer_tuid_from_path(path: Path) -> str | None:
    """Infer Quantify TUID from a dataset directory name in the path."""
    for part in path.parts:
        match = TUID_DIR_PREFIX_PATTERN.match(part)
        if match is None:
            continue
        tuid = match.group("tuid").strip()
        if tuid:
            return tuid
    return None
