import os
from pathlib import Path
from typing import Dict

from dotenv import load_dotenv

# ROOT: /var/www/html/flask_server
ROOT_DIR = Path(__file__).resolve().parents[0].parent
ENV_PATH = ROOT_DIR / ".env"

# Cargar .env (por si aún no está cargado)
if ENV_PATH.exists():
    load_dotenv(ENV_PATH)


def _parse_users(raw: str) -> Dict[str, str]:
    """
    Parsea la variable WP_INVOICES_MAIL_USERS con formato:
      user1:pass1,user2:pass2,...
    y devuelve un dict {user: pass}.
    """
    users: Dict[str, str] = {}
    if not raw:
        return users

    for item in raw.split(","):
        item = item.strip()
        if not item or ":" not in item:
            continue
        user, pwd = item.split(":", 1)
        user = user.strip()
        pwd = pwd.strip()
        if user and pwd:
            users[user] = pwd
    return users


def get_allowed_users() -> Dict[str, str]:
    raw = os.getenv("WP_INVOICES_MAIL_USERS", "")
    return _parse_users(raw)


def check_credentials(user: str, password: str) -> bool:
    """
    Devuelve True si user/password está en la lista de usuarios permitidos.
    """
    if not user or not password:
        return False
    users = get_allowed_users()
    expected = users.get(user)
    return expected is not None and expected == password
