from __future__ import annotations
import copy
import json
from pathlib import Path
from typing import Any

PACKAGE_ROOT = Path(__file__).resolve().parents[1]
DEFAULT_CONFIG = PACKAGE_ROOT / "config" / "grav_bridge_i_analysis_specification.json"


def load_config(path: str | Path | None = None, overrides: dict[str, Any] | None = None) -> dict[str, Any]:
    config_path = Path(path) if path else DEFAULT_CONFIG
    data = json.loads(config_path.read_text(encoding="utf-8"))
    if overrides:
        data = deep_merge(data, overrides)
    return data


def deep_merge(base: dict[str, Any], updates: dict[str, Any]) -> dict[str, Any]:
    result = copy.deepcopy(base)
    for key, value in updates.items():
        if isinstance(value, dict) and isinstance(result.get(key), dict):
            result[key] = deep_merge(result[key], value)
        else:
            result[key] = value
    return result


def resolve_registered_path(config: dict[str, Any], key: str) -> Path:
    value = config["registered_inputs"][key]
    path = Path(value)
    return path if path.is_absolute() else PACKAGE_ROOT / path
