import pathlib
from functools import cached_property
from typing import Self

from pydantic import BaseModel


def _reverse_mapping(d: dict[str, str]) -> dict[str, str]:
    if len(set(d.values())) != len(d):
        raise ValueError("Cannot use reverse mapping if values are not unique")

    return {v: k for k, v in d.items()}


class UmlautConfig(BaseModel):
    comment_mapping: dict[str, str] = {}
    string_mapping: dict[str, str] = {}
    char_mapping: dict[str, str] = {}

    @cached_property
    def reverse_string_mapping(self) -> dict[str, str]:
        return _reverse_mapping(self.string_mapping)

    @cached_property
    def reverse_char_mapping(self) -> dict[str, str]:
        return _reverse_mapping(self.string_mapping)

    @classmethod
    def from_path(cls, path: str | pathlib.Path) -> Self:
        path = pathlib.Path(path)

        return cls.model_validate_json(path.read_bytes())
