"""Infrastructure implementations for updater ports."""

import configparser
import json
import logging
from pathlib import Path

import toml

from config_inspector.updaters.application.ports import ConfigUpdater

logger = logging.getLogger(__name__)


class IniConfigUpdater(ConfigUpdater):
    """Updates INI configuration files with validation."""

    def update(self, filepath: Path, content: str) -> None:
        config = configparser.ConfigParser()
        try:
            config.read_string(content)
        except configparser.MissingSectionHeaderError as err:
            logger.warning("INI decode error: %s", err)
            raise

        filepath.write_text(content, encoding="utf8", errors="replace")


class TomlConfigUpdater(ConfigUpdater):
    """Updates TOML configuration files with merging."""

    def update(self, filepath: Path, content: dict) -> None:
        try:
            existing = toml.loads(filepath.read_text(encoding="utf8"))
        except toml.TomlDecodeError as err:
            logger.warning("TOML decode error: %s", err)
            raise

        existing.update(content)
        filepath.write_text(toml.dumps(existing), encoding="utf8", errors="replace")


class JsonConfigUpdater(ConfigUpdater):
    """Updates JSON configuration files with merging."""

    def update(self, filepath: Path, content: dict) -> None:
        try:
            existing = json.loads(filepath.read_text(encoding="utf8"))
        except json.JSONDecodeError as err:
            logger.warning("JSON decode error: %s", err)
            raise

        existing.update(content)
        filepath.write_text(
            json.dumps(existing, indent=4), encoding="utf8", errors="replace"
        )


class PlainTextUpdater(ConfigUpdater):
    """Updates plain text files without validation."""

    def update(self, filepath: Path, content: str) -> None:
        filepath.write_text(content, encoding="utf8", errors="replace")
