"""Lightweight anti-spam checks for the public platform lead form.

Two signals, both checked server side before a lead is logged or mailed:

- honeypot: a field hidden from people (``HONEYPOT_FIELD``); bots that fill
  every input give themselves away;
- form token: a signed render timestamp (``FORM_TOKEN_FIELD``) proving the
  POST comes from a rendered form and was not submitted implausibly fast.
  A bare scripted POST to the endpoint has no valid token.

Detected spam (honeypot, too fast) gets the same response as a real lead, so
the rules are not revealed. A missing, forged or expired token gets a generic
"reload the page" error, so a visitor with a stale page does not lose a lead
silently. Security logs record only a reason code, never contact data or the
message.
"""
from __future__ import annotations

import re
from datetime import datetime, timezone

from flask import current_app
from itsdangerous import BadSignature, SignatureExpired, URLSafeTimedSerializer

from InvestmentWebsite.offers.platform_facade import safe_http_url

HONEYPOT_FIELD = "website"
FORM_TOKEN_FIELD = "form_token"

_TOKEN_SALT = "platform-lead-form-v1"
# Faster than a person can type a message.
MIN_FILL_SECONDS = 3
# Rendered pages may be cached (max-age 300 + stale 600) or left open in a tab.
MAX_TOKEN_AGE_SECONDS = 7 * 24 * 3600

MAX_MESSAGE_LENGTH = 3000
MAX_EMAIL_LENGTH = 254
MAX_PHONE_LENGTH = 32
MAX_URL_LENGTH = 2048
MIN_PHONE_DIGITS = 6
_PHONE_ALLOWED = re.compile(r"^[0-9+()\-./ ]+$")


def _serializer() -> URLSafeTimedSerializer:
    return URLSafeTimedSerializer(current_app.secret_key, salt=_TOKEN_SALT)


def issue_form_token() -> str:
    return _serializer().dumps({"f": "lead"})


def check_form_token(token: str | None) -> str | None:
    """Reason code when the token is unusable, otherwise None."""
    if not token:
        return "missing_token"
    try:
        _, signed_at = _serializer().loads(token, max_age=MAX_TOKEN_AGE_SECONDS, return_timestamp=True)
    except SignatureExpired:
        return "expired_token"
    except BadSignature:
        return "invalid_token"
    age = (datetime.now(timezone.utc) - signed_at).total_seconds()
    if age < MIN_FILL_SECONDS:
        return "too_fast"
    return None


def detect_spam(form) -> str | None:
    """Reason code for a submission to drop silently, otherwise None."""
    if (form.get(HONEYPOT_FIELD) or "").strip():
        return "honeypot"
    return None


def _is_http_url(value: str) -> bool:
    # Use the storage URL contract as a predicate, never as a replacement for
    # invalid input. This also rejects malformed URLs without raising a 500.
    return bool(safe_http_url(value))


def validate_lead_limits(payload: dict) -> tuple[str | None, str | None]:
    """Length and format limits; messages stay generic for the visitor."""
    if len(payload["message"]) > MAX_MESSAGE_LENGTH:
        return "message_too_long", f"Wiadomość może mieć maksymalnie {MAX_MESSAGE_LENGTH} znaków."
    if len(payload["email"]) > MAX_EMAIL_LENGTH:
        return "invalid_email", "Invalid email address."
    phone = payload["phone"]
    if phone:
        digits = sum(ch.isdigit() for ch in phone)
        if len(phone) > MAX_PHONE_LENGTH or not _PHONE_ALLOWED.match(phone) or digits < MIN_PHONE_DIGITS:
            return "invalid_phone", "Nieprawidłowy numer telefonu."
    for key in ("offer_url", "platform_page_url"):
        value = (payload.get(key) or "").strip()
        if value and (len(value) > MAX_URL_LENGTH or not _is_http_url(value)):
            return "invalid_url", "Invalid request."
    return None, None


def security_log_data(now, payload: dict, reason: str) -> dict:
    """Security log entry without contact data or message content."""
    return {
        "timestamp": str(now),
        "ip": payload["ip"],
        "platform": payload["platform"][:40],
        "event": "lead_spam_blocked",
        "status": "blocked",
        "reason": reason,
    }
