import re
from pathlib import PurePosixPath
from urllib.parse import unquote, urlparse


_KEY_PART_RE = re.compile(r"^[A-Za-z0-9._&-]{1,96}$")


def _key(kind: str, source: str, stable_id) -> str | None:
    value = str(stable_id or "").strip()
    if not _KEY_PART_RE.fullmatch(value):
        return None
    return f"{kind}:v1:{source}:{value}"


def investment_offer_key(offer_id) -> str | None:
    try:
        value = int(offer_id)
    except (TypeError, ValueError):
        return None
    return _key("offer", "investment", value) if value > 0 else None


def tripinvest_offer_key(source_url: str | None) -> str | None:
    try:
        path = urlparse(str(source_url or "")).path.rstrip("/")
    except ValueError:
        return None
    match = re.search(r"-(\d+)$", path)
    return _key("offer", "tripinvest", match.group(1)) if match else None


def avarten_offer_key(canonical_offer: dict | None) -> str | None:
    identity = (canonical_offer or {}).get("identity") or {}
    return _key("offer", "avarten", identity.get("offer_id"))


def cyprus_project_key(project_url: str | None) -> str | None:
    try:
        path = urlparse(str(project_url or "")).path
    except ValueError:
        return None
    slug = unquote(PurePosixPath(path).name).replace("&amp;", "&").strip().lower()
    return _key("project", "cyprus", slug)
