"""Central CSRF protection for the CRM blueprint: Fetch Metadata + Origin/Referer, fail-closed.

Threat model: the CRM authenticates with a cookie, so any other site can make the victim's browser send a request that carries it
(form POST, fetch with credentials, link navigation). Browsers always label such requests: every engine in use sends
`Sec-Fetch-Site`, and `Origin` on every non-GET request (form, fetch, XHR). A mutating request that carries NEITHER (and no
usable Referer) is therefore not a same-origin browser request; it is rejected instead of being trusted. Non-browser clients
cannot be driven by a victim's browser, so rejecting them costs nothing (the CRM has no scripted HTTP clients).

Rules for POST/PUT/PATCH/DELETE (login included):
  1. `Sec-Fetch-Site` present  -> must be `same-origin` (or `none`, as in the export guards); `same-site` (a sibling subdomain) and
     `cross-site` are rejected.
  2. `Origin` present          -> its host[:port] must equal the request host (also when rule 1 passed: the two must agree;
     `Origin: null` is rejected).
  3. `Referer` present         -> its host must equal the request host (also when 1/2 passed: contradictory labels are rejected).
  4. No label at all           -> reject (`origin_required`); a same-origin Referer alone is accepted as the fallback.
GET /crm/logout is state-changing, so it gets the label check of rule 1/2/3 relaxed for navigations: a missing label is accepted
(typing the URL, old browsers), a present cross-site/same-site label or a foreign Origin/Referer is rejected.

The host is compared WITHOUT the scheme so the guard does not depend on how the front proxy reports https to the application.
Token-based export/scheduler protections stay as they are and run after this guard (it only adds a layer).
No front-end change is needed: same-origin fetch/forms already send these headers.
"""
from urllib.parse import urlsplit

from flask import request

UNSAFE_METHODS = frozenset({'POST', 'PUT', 'PATCH', 'DELETE'})
SAME_ORIGIN_SITES = frozenset({'same-origin', 'none'})
LOGOUT_ENDPOINT = 'investmentmanager.logout'


def _host_of(value):
    try:
        return urlsplit(value).netloc.lower()
    except ValueError:
        return ''


def origin_violation(method=None, endpoint=None):
    """None when the request may proceed, else a short reason code (`origin_forbidden` / `origin_required`)."""
    method = method or request.method
    endpoint = endpoint if endpoint is not None else request.endpoint
    mutating = method in UNSAFE_METHODS
    if not mutating and not (method == 'GET' and endpoint == LOGOUT_ENDPOINT):
        return None

    site = request.headers.get('Sec-Fetch-Site')
    origin = request.headers.get('Origin')
    referer = request.headers.get('Referer')
    host = request.host.lower()

    if site is not None and site.lower() not in SAME_ORIGIN_SITES:
        return 'origin_forbidden'
    if origin is not None and (origin == 'null' or _host_of(origin) != host):
        return 'origin_forbidden'
    if referer is not None and _host_of(referer) != host:
        return 'origin_forbidden'                       # every label that is present must agree; a browser never mixes them
    if site is None and origin is None and referer is None:
        return 'origin_required' if mutating else None
    return None
