"""
Чтение конфигурации из config.php (AegisOne сайт).

Парсит PHP define() константы и возвращает их как dict.
Fallback на hardcoded значения если файл не найден.
"""
from __future__ import annotations
import re
import os
from typing import Optional, List, Tuple
from app.config import settings


class ConfigReader:
    def __init__(self):
        self._cache = {}
        self._loaded = False

    def load(self, path: Optional[str] = None) -> dict:
        filepath = path or settings.config_php_path
        if not os.path.isfile(filepath):
            return self._fallback()

        with open(filepath, "r", encoding="utf-8") as f:
            content = f.read()

        constants = {}
        pattern = re.compile(r"define\(\s*'(\w+)'\s*,\s*'([^']*)'\s*\)")
        for match in pattern.finditer(content):
            constants[match.group(1)] = match.group(2)

        self._cache = constants
        self._loaded = True
        return constants

    def _fallback(self) -> dict:
        self._cache = {
            "PHONE_MAIN": "+7 (861) 203-33-30",
            "PHONE_MAIN_LINK": "+78612033330",
            "PHONE_SECOND": "+7 (995) 203-33-30",
            "PHONE_SECOND_LINK": "+79952033330",
            "SITE_MAIL": "mail@aegisone.ru",
            "SITE_MAIL_FROM": "no-reply@aegisone.ru",
            "SITE_MAIL_TO": "mail@aegisone.ru",
        }
        self._loaded = True
        return self._cache

    def get(self, key: str, default: str = "") -> str:
        if not self._loaded:
            self.load()
        return self._cache.get(key, default)

    def get_phones(self) -> List[Tuple[str, str]]:
        return [
            (self.get("PHONE_MAIN"), self.get("PHONE_MAIN_LINK")),
            (self.get("PHONE_SECOND"), self.get("PHONE_SECOND_LINK")),
        ]

    def get_site_mail(self) -> str:
        return self.get("SITE_MAIL", "mail@aegisone.ru")

    def get_mail_from(self) -> str:
        return self.get("SITE_MAIL_FROM", "no-reply@aegisone.ru")


config_reader = ConfigReader()
