"""Legacy invoice-form credential compatibility.

This module exists only for the current HTML upload form. Platform API access
uses the RS256 gateway and must not call these helpers.
"""

from __future__ import annotations

import hmac
import os


def _parse_users(raw: str) -> dict[str, str]:
    users: dict[str, str] = {}
    for item in (raw or "").split(","):
        candidate = item.strip()
        if not candidate or ":" not in candidate:
            continue
        username, password = candidate.split(":", 1)
        username = username.strip()
        password = password.strip()
        if username and password:
            users[username] = password
    return users


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


def check_credentials(user: str, password: str) -> bool:
    """Compare legacy form credentials without timing-sensitive equality."""
    if not user or not password:
        return False
    expected = get_allowed_users().get(user)
    return expected is not None and hmac.compare_digest(expected, password)
