import pathlib
from typing import Self

from pydantic import BaseModel

from my_mcp.umlaut_config import UmlautConfig


class EncodingConfig(BaseModel):
    default: str = "utf-8"
    mapping: dict[str, str] = {}

    def find_encoding(self, path: pathlib.Path) -> str:
        for pattern, encoding in self.mapping.items():
            if path.match(pattern):
                return encoding
        return self.default


class ServerConfig(BaseModel):
    umlaut_config: UmlautConfig = UmlautConfig()
    encoding_config: EncodingConfig = EncodingConfig()

    def encoding_for(self, path: str) -> str:
        return self.encoding_config.find_encoding(pathlib.Path(path))

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