"""The five active FTP profiles and their environment keys. No Streamlit, no hosts from the browser.

Key names, the 21 default port and the 20 s default timeout match the existing IDBManager.
Nothing here reads configuration at import. Values are never logged or returned; only the
names of missing keys are reported. A foreign TabelaOfert profile never falls back to the
Polish account. Otodom is inactive (D07) and absent on purpose.
"""
from dataclasses import dataclass
from pathlib import Path
import os

DEFAULT_PORT = 21
DEFAULT_TIMEOUT = 20.0
# profile -> (environment prefix, Domiporta-style rename prefix, FTPS)
PROFILES = {
    'no': ('FTP_NO', '', False),
    'domiporta': ('FTP_DOMIPORTA', 'ok-', False),
    'tabelaofert': ('FTP_TABELAOFERT', '', False),
    'tabelaofert_primary': ('FTP_TABELAOFERT_PRIMARY', '', False),
    'gruntguru': ('FTP_GRUNTGURU', '', False),
}
DOMESTIC_PROFILE = {'no': 'no', 'domiporta': 'domiporta', 'tabelaofert': 'tabelaofert', 'gruntguru': 'gruntguru'}
FOREIGN_PROFILE = {'domiporta': 'domiporta', 'tabelaofert': 'tabelaofert_primary'}


class ConfigError(Exception):
    def __init__(self, code, missing=()):
        super().__init__(code)
        self.code = code
        self.missing = tuple(missing)


@dataclass(frozen=True)
class PortalConfig:
    profile: str
    host: str
    port: int
    username: str
    password: str
    use_tls: bool
    ready_prefix: str
    timeout_seconds: float

    def __repr__(self):                       # never expose credentials through repr/logging
        return f'PortalConfig(profile={self.profile!r}, port={self.port}, tls={self.use_tls})'


# The scheduler (cron) never loads the application's .env, so the executor reads it itself - lazily, only when one of
# the allowed keys is asked for, and never into the global environment, logs or diagnostics.
ENV_FILE = Path(__file__).resolve().parents[2] / '.env'
COMPANY_KEYS = ('GRUNTGURU_ESTICRM_COMPANY_ID', 'GRUNTGURU_ESTICRM_COMPANY_NAME',
                'ESTICRM_COMPANY_ID', 'ESTICRM_COMPANY_NAME')            # same names as domestic_packages.COMPANY_KEYS
FOREIGN_PACKAGE_KEYS = ('FOREIGN_MEDIA_HOST_PINS',)
ALLOWED_KEYS = frozenset(f'{prefix}_{name}' for prefix, _, _ in PROFILES.values()
                         for name in ('HOST', 'PORT', 'USERNAME', 'PASSWORD', 'TIMEOUT')) | frozenset(COMPANY_KEYS) | frozenset(FOREIGN_PACKAGE_KEYS)


def _file_value(key):
    """Value of one allowed key from the .env file, or None. Never raises, never logs, keeps nothing."""
    if key not in ALLOWED_KEYS:
        return None
    try:
        from dotenv import dotenv_values
        value = dotenv_values(ENV_FILE, encoding='utf-8-sig').get(key)
    except Exception:                                    # missing/unreadable/corrupt file or no python-dotenv: "not set"
        return None
    return value if isinstance(value, str) and value.strip() else None


def environment_getter(key):
    """Process environment first (WSGI already loaded .env into it), then the allowed keys of the .env file."""
    value = os.environ.get(key)
    return value if value else _file_value(key)


def company_settings(getter=environment_getter):
    return {key: getter(key) for key in COMPANY_KEYS}


def profile_for(domain, portal, binding=None):
    """Logical portal -> transport profile. Foreign profile must agree with the verified manifest."""
    table = FOREIGN_PROFILE if domain == 'foreign' else DOMESTIC_PROFILE
    profile = table.get(portal)
    if profile is None:
        raise ConfigError('config_invalid')
    if binding is not None and domain == 'foreign' and binding.get('transport_profile') != profile:
        raise ConfigError('config_invalid')
    return profile


def _keys(profile):
    if profile not in PROFILES:
        raise ConfigError('config_invalid')
    prefix = PROFILES[profile][0]
    return {name: f'{prefix}_{name}' for name in ('HOST', 'PORT', 'USERNAME', 'PASSWORD', 'TIMEOUT')}


def missing_keys(profile, secret_getter=environment_getter):
    """Names (not values) of the mandatory keys that are empty."""
    keys = _keys(profile)
    return [keys[name] for name in ('HOST', 'USERNAME', 'PASSWORD') if not secret_getter(keys[name])]


def profile_status(profile, secret_getter=environment_getter):
    missing = missing_keys(profile, secret_getter)
    return {'profile': profile, 'complete': not missing, 'missing': missing}


def load_profile(profile, secret_getter=environment_getter):
    keys = _keys(profile)
    missing = missing_keys(profile, secret_getter)
    if missing:
        raise ConfigError('config_missing', missing)
    try:
        raw_port = secret_getter(keys['PORT'])
        port = DEFAULT_PORT if raw_port in (None, '') else int(str(raw_port).strip())
        raw_timeout = secret_getter(keys['TIMEOUT'])
        timeout = DEFAULT_TIMEOUT if raw_timeout in (None, '') else float(str(raw_timeout).strip())
    except (TypeError, ValueError):
        raise ConfigError('config_invalid') from None
    if not 0 < port < 65536 or not 0 < timeout <= 600:
        raise ConfigError('config_invalid')
    _, ready_prefix, tls = PROFILES[profile]
    return PortalConfig(profile, str(secret_getter(keys['HOST'])), port, str(secret_getter(keys['USERNAME'])),
                        str(secret_getter(keys['PASSWORD'])), tls, ready_prefix, timeout)
