"""Feather configuration file"""

import os
import tomllib
from zoneinfo import ZoneInfo
from pathlib import Path
from jinja2 import Template

default_config_path: Path = Path(__file__).parent / "config.default.toml"


class ConfigurationError(ValueError):
    pass


class Config:
    def __init__(self):
        with default_config_path.open("rb") as f:
            default_config = tomllib.load(f)

        config_path = Path(os.environ.get("CONFIG_PATH") or "config.toml")
        if config_path.exists():
            with config_path.open("rb") as f:
                config = tomllib.load(f)
        elif "CONFIG_PATH" in os.environ:
            raise ConfigurationError(
                f"configuration file {config_path} does not exist; create it or change the CONFIG_PATH environment variable to another path"
            )
        else:
            config = {}

        def get_config(category, field, can_default=True):
            env_name = f"{category.upper()}_{field.upper()}"
            c = config.get(category, {})
            if env_name in os.environ:
                return os.environ[env_name]
            elif field in c:
                return c[field]
            elif can_default:
                return default_config[category][field]
            else:
                raise ConfigurationError(
                    f"{category}.{field} required but not found in configuration file {config_path} nor in environment variable {env_name}"
                )

        # Get config fields
        self.html_root: Path = Path(get_config("directories", "reader"))
        self.json_root: Path = Path(get_config("directories", "data"))

        self.server_api: str = str(get_config("server", "api", False))
        if self.server_api not in ("googlereader", "ttrss"):
            raise ConfigurationError(
                f"server.api must be either ttrss or googlereader, not {self.server_api}"
            )
        self.server_url: str = str(get_config("server", "url", False))
        self.server_user: str = str(get_config("server", "user", False))
        self.server_password: str = str(get_config("server", "password", False))
        self.articles_per_query: int = int(get_config("server", "articles_per_request"))
        if self.articles_per_query == 0:
            self.articles_per_query = 1000 if self.server_api == "googlereader" else 200
        self.only_sync_unread_articles: bool = bool(
            get_config("server", "only_sync_unread_articles")
        )
        self.keep_read_articles_for: float = float(
            get_config("server", "keep_read_articles_for")
        )

        self.timezone: ZoneInfo = ZoneInfo(str(get_config("datetime", "timezone")))
        self.time_format: str = str(get_config("datetime", "format"))

        self.write_read_articles: bool = bool(get_config("html", "write_read_articles"))
        self.article_template: Template = Template(
            str(get_config("html", "article_template")), autoescape=True
        )
        self.article_filename_template: Template = Template(
            str(get_config("html", "filename_template")), autoescape=False
        )
        self.article_category_template: Template = Template(
            str(get_config("html", "category_template")), autoescape=False
        )
        self.hide_empty_categories: bool = bool(
            get_config("html", "hide_empty_categories")
        )
        self.max_filename_length: int = int(get_config("html", "max_filename_length"))
        self.filename_translation = str.maketrans(
            get_config("html", "filename_replacement")
        )

        self.daemon_sync_up_every: float = float(get_config("daemon", "sync_up_every"))
        self.daemon_sync_down_every: float = float(
            get_config("daemon", "sync_down_every")
        )
        self.daemon_watch_files: bool = bool(get_config("daemon", "watch_files"))
        self.daemon_sync_up_every_when_used: float = float(
            get_config("daemon", "sync_up_every_when_used")
        )
        if self.daemon_sync_up_every < self.daemon_sync_up_every_when_used:
            raise ConfigurationError(
                "daemon.daemon_sync_up_every must be greater or equal to daemon.sync_up_every_when_used"
            )
        self.daemon_sync_down_every_when_used: float = float(
            get_config("daemon", "sync_down_every_when_used")
        )
        if self.daemon_sync_down_every < self.daemon_sync_down_every_when_used:
            raise ConfigurationError(
                "daemon.daemon_sync_down_every must be greater or equal to daemon.sync_down_every_when_used"
            )

        # Create missing directories
        self.html_root.mkdir(exist_ok=True)
        self.json_root.mkdir(exist_ok=True)
