from __future__ import annotations

import json
from pathlib import Path
from typing import Any


SCRIPT_DIR = Path(__file__).resolve().parent


def load_config(config_path: str | Path = "camera_recorder_config.json") -> tuple[dict[str, Any], Path]:
    path = Path(config_path)
    if not path.is_absolute():
        if path.exists():
            path = path.resolve()
        else:
            path = (SCRIPT_DIR / path).resolve()

    with path.open("r", encoding="utf-8") as handle:
        return json.load(handle), path.parent


def load_json_file(path: str | Path) -> dict[str, Any]:
    with Path(path).open("r", encoding="utf-8") as handle:
        return json.load(handle)


def resolve_path(config_dir: Path, raw_path: str | Path) -> Path:
    path = Path(raw_path)
    if path.is_absolute():
        return path
    if path.exists():
        return path.resolve()
    return (config_dir / path).resolve()


def resolve_default_model(config: dict[str, Any], config_dir: Path) -> str:
    path_cfg = config["paths"]
    for raw_path in path_cfg["default_model_candidates"]:
        candidate = resolve_path(config_dir, raw_path)
        if candidate.exists():
            return str(candidate)
    return path_cfg["model_fallback"]


def load_mapper_configs(config: dict[str, Any], config_dir: Path) -> tuple[dict[str, Any], dict[str, Any], Path, Path]:
    path_cfg = config["paths"]
    joint_path = resolve_path(config_dir, path_cfg["joint_config"])
    pose_mapping_path = resolve_path(config_dir, path_cfg["pose_mapping_config"])
    return (
        load_json_file(joint_path),
        load_json_file(pose_mapping_path),
        joint_path,
        pose_mapping_path,
    )
