import os
import sys
from configparser import ConfigParser, ExtendedInterpolation
from pathlib import Path
from typing import List

from typing_extensions import Self


class BaseConfig(ConfigParser):

    def __init__(self, name: str, encoding='utf-8') -> Self:
        super().__init__(
            interpolation=ExtendedInterpolation(),
            strict=True,
            inline_comment_prefixes=['#', ';'],
            empty_lines_in_values=True
        )
        self.name, self.platform = name, sys.platform.lower()
        self._initpaths()
        self.read(self.paths, encoding=encoding)

    def _initpaths(self) -> None:
        self._paths: List[Path] = []
        match self.platform:
            case "linux":
                self.paths = Path('/etc')/self.name
                self.paths = Path(os.environ.get('HOME'))/"etc"/self.name
            case "win32":
                self.paths = Path(os.environ['ProgramData'])/self.name
                self.paths = Path(os.environ['APPDATA'])/self.name
            case _:
                raise NotImplementedError(f'没有实现的平台: {self.platform=}')
        self.paths = Path(self.name)

    @property
    def paths(self) -> List[Path]:
        return self._paths

    @paths.setter
    def paths(self, value: Path | str) -> None:
        self._paths.append(Path(value))

    def show(self) -> None:
        paths = self.paths
        for path in paths:
            print(path.absolute())

    def _append(self, value: Path, encoding='utf-8') -> None:
        self.paths = value
        self.read(Path(value), encoding=encoding)

    def overwrite(self, values: List[Path | str] | Path | str, encoding='utf-8') -> Self:
        self.clear()
        self._paths = []
        if isinstance(values, (Path, str)):
            values = [Path(values)]
        for value in values:
            self._append(value)
        return self
