"""
cloudflare_api.py
=================

PURPOSE
-------
All communication with the Cloudflare v4 API lives here. The bot logic asks
this module questions like "what's the Zone ID for example.com?" or "update
this redirect to point at https://new.com" and never has to know the URL
shapes or JSON structures involved.

THE TWO KINDS OF REDIRECTS WE SUPPORT
-------------------------------------
Cloudflare has several redirect features. This bot manages the two most common:

1) ZONE-LEVEL "SINGLE REDIRECTS"
   These live *inside one domain (zone)* and are implemented with Cloudflare's
   Rulesets engine, in a phase called "http_request_dynamic_redirect".
   Think: "redirect old.example.com to https://example.com".

2) ACCOUNT-LEVEL "BULK REDIRECTS"
   These live at the *account* level (shared across all your domains) and are
   stored as items inside a "Bulk Redirect List". Each item maps a
   source_url to a target_url. Think: a big spreadsheet of redirects.

Our workflow checks #1 first; if nothing matches, it falls back to #2.

AUTHENTICATION
--------------
Every request sends the header:

    Authorization: Bearer <CLOUDFLARE_API_TOKEN>

Cloudflare replies with JSON shaped like:

    { "success": true/false, "errors": [...], "messages": [...], "result": ... }

We check "success" and raise CloudflareError on failure so the bot logic can
show the user a clean message.
"""

import logging

import requests

from config import (
    CLOUDFLARE_API_BASE,
    CLOUDFLARE_API_TOKEN,
    HTTP_TIMEOUT,
)

log = logging.getLogger(__name__)


# The Rulesets "phase" name that holds Single Redirects. Cloudflare uses this
# exact string; do not change it.
DYNAMIC_REDIRECT_PHASE = "http_request_dynamic_redirect"


class CloudflareError(Exception):
    """
    A custom exception we raise whenever Cloudflare reports a problem.

    Using our own exception type (instead of a generic Exception) lets the bot
    logic catch *just* Cloudflare errors and turn them into a friendly Telegram
    message, while letting unexpected bugs bubble up normally.
    """
    pass


def _headers() -> dict:
    """Build the standard auth + content-type headers for every request."""
    return {
        "Authorization": f"Bearer {CLOUDFLARE_API_TOKEN}",
        "Content-Type": "application/json",
    }


def _request(method: str, path: str, **kwargs) -> dict:
    """
    Low-level helper that sends one request to the Cloudflare API.

    Parameters
    ----------
    method : str
        HTTP verb: "GET", "POST", "PUT", "PATCH", "DELETE".
    path : str
        The path AFTER the base, e.g. "/zones?name=example.com".
    **kwargs :
        Extra arguments forwarded to requests (most often json=... for bodies).

    Returns
    -------
    dict
        The full parsed JSON response (the whole envelope, not just "result").

    Raises
    ------
    CloudflareError
        If the network call fails OR Cloudflare returns "success": false.
    """
    url = f"{CLOUDFLARE_API_BASE}{path}"

    try:
        response = requests.request(
            method,
            url,
            headers=_headers(),
            timeout=HTTP_TIMEOUT,
            **kwargs,
        )
    except requests.RequestException as exc:
        # Could not even reach Cloudflare.
        log.exception("Network error calling Cloudflare: %s", exc)
        raise CloudflareError(f"Could not reach Cloudflare: {exc}") from exc

    # Try to decode JSON. Some error pages might not be JSON, so guard it.
    try:
        data = response.json()
    except ValueError:
        raise CloudflareError(
            f"Cloudflare returned non-JSON (HTTP {response.status_code})."
        )

    # The "success" flag is Cloudflare's master pass/fail switch.
    if not data.get("success", False):
        # Collect human-readable error messages to show the user.
        errors = data.get("errors", [])
        # Each error is like {"code": 1001, "message": "..."}.
        msg = "; ".join(e.get("message", str(e)) for e in errors) or "Unknown error"
        log.error("Cloudflare API error on %s %s: %s", method, path, msg)
        raise CloudflareError(msg)

    return data


# ===========================================================================
# STEP 1 — Find the Zone ID for a domain
# ===========================================================================

def get_zone_id(domain: str) -> str | None:
    """
    Look up the Zone ID for a domain name.

    A "zone" in Cloudflare IS basically a domain (e.g. example.com). Almost
    every other API call needs the zone's ID, not its name, so this is usually
    our first step.

    API CALL:
        GET /zones?name=example.com

    Parameters
    ----------
    domain : str
        The domain name, e.g. "example.com".

    Returns
    -------
    str  -> the zone id if the domain is in this Cloudflare account.
    None -> if no matching zone was found.
    """
    # The "name" query parameter filters zones by exact domain name.
    data = _request("GET", f"/zones?name={domain}")

    # "result" is a list of matching zones (0 or 1 for an exact name match).
    results = data.get("result", [])
    if not results:
        return None

    # The first match's "id" is the Zone ID we want.
    return results[0]["id"]


# ===========================================================================
# STEP 2 — Zone-level Single Redirects (Rulesets engine)
# ===========================================================================

def get_dynamic_redirect_ruleset(zone_id: str) -> dict | None:
    """
    Fetch the zone's Single-Redirect ruleset (the "entrypoint" ruleset for the
    dynamic-redirect phase). This ruleset holds all of the zone's single
    redirect rules.

    API CALL:
        GET /zones/{zone_id}/rulesets/phases/http_request_dynamic_redirect/entrypoint

    Returns
    -------
    dict  -> the ruleset object (it has an "id" and a "rules" list).
    None  -> if the zone has no single-redirect ruleset yet (no redirects set).
    """
    path = (
        f"/zones/{zone_id}/rulesets/phases/"
        f"{DYNAMIC_REDIRECT_PHASE}/entrypoint"
    )
    try:
        data = _request("GET", path)
    except CloudflareError:
        # If the phase has never been used, Cloudflare returns an error rather
        # than an empty ruleset. We treat "no ruleset" as None so the caller
        # can fall back to bulk redirects.
        return None

    return data.get("result")


def find_zone_redirect_rule(zone_id: str, domain: str) -> tuple[str, dict] | None:
    """
    Search the zone's single-redirect rules for one that mentions our domain.

    HOW MATCHING WORKS:
        Each rule has an "expression" string like:
            (http.host eq "old.example.com")
        We simply check whether the domain text appears inside that expression.
        This is a pragmatic, beginner-friendly heuristic — it catches the
        common cases without writing a full expression parser.

    Parameters
    ----------
    zone_id : str
    domain : str

    Returns
    -------
    (ruleset_id, rule_dict)  -> if a matching rule is found.
    None                      -> if no rule matches (caller should try bulk).
    """
    ruleset = get_dynamic_redirect_ruleset(zone_id)
    if not ruleset:
        return None

    ruleset_id = ruleset["id"]

    # "rules" may be missing if the ruleset is empty; default to [].
    for rule in ruleset.get("rules", []):
        # The expression is where the matched hostname/path lives.
        expression = rule.get("expression", "")

        # Case-insensitive "does the domain appear in this rule?" check.
        if domain.lower() in expression.lower():
            return ruleset_id, rule

    return None


def describe_zone_rule(rule: dict) -> str:
    """
    Turn a single-redirect rule into a short human-readable summary for chat.

    We dig into the nested action_parameters to find the current target URL
    and status code. The structure looks like:

        rule["action_parameters"]["from_value"]["target_url"]["value"]   (static)
        rule["action_parameters"]["from_value"]["target_url"]["expression"] (dynamic)
        rule["action_parameters"]["from_value"]["status_code"]
    """
    params = rule.get("action_parameters", {})
    from_value = params.get("from_value", {})
    target = from_value.get("target_url", {})

    # A redirect target is EITHER a fixed "value" or a dynamic "expression".
    current_target = target.get("value") or target.get("expression") or "(unknown)"
    status_code = from_value.get("status_code", "(default)")

    return (
        f"<b>Match expression:</b> <code>{rule.get('expression', '')}</code>\n"
        f"<b>Current target:</b> <code>{current_target}</code>\n"
        f"<b>Status code:</b> <code>{status_code}</code>"
    )


def update_zone_redirect_rule(zone_id: str, ruleset_id: str, rule: dict,
                              new_target_url: str) -> dict:
    """
    Change the target URL of an existing single-redirect rule.

    STRATEGY:
        We take the rule we already fetched, overwrite its target URL with the
        new one (keeping the status code and other options), and send it back
        with a PATCH. PATCHing a rule replaces that rule's definition.

    API CALL:
        PATCH /zones/{zone_id}/rulesets/{ruleset_id}/rules/{rule_id}

    Parameters
    ----------
    zone_id : str
    ruleset_id : str
    rule : dict
        The rule object we got from find_zone_redirect_rule.
    new_target_url : str
        The URL the user wants to redirect to now.

    Returns
    -------
    dict
        The updated ruleset returned by Cloudflare.
    """
    rule_id = rule["id"]

    # Start from the existing parameters so we keep status_code, query-string
    # preservation, etc. We use .copy()/dict() to avoid mutating the original.
    params = dict(rule.get("action_parameters", {}))
    from_value = dict(params.get("from_value", {}))

    # Overwrite the target with a STATIC value (a plain URL). If the original
    # used a dynamic "expression", we replace it with a simple value, which is
    # what a beginner almost always wants. We note this in the README.
    from_value["target_url"] = {"value": new_target_url}

    params["from_value"] = from_value

    # The PATCH body is the rule fields we want to set.
    body = {
        "action": rule.get("action", "redirect"),
        "action_parameters": params,
        "expression": rule.get("expression", ""),
        "description": rule.get("description", ""),
        # Keep it enabled unless it was explicitly disabled.
        "enabled": rule.get("enabled", True),
    }

    path = f"/zones/{zone_id}/rulesets/{ruleset_id}/rules/{rule_id}"
    data = _request("PATCH", path, json=body)
    return data.get("result", {})


# ===========================================================================
# STEP 3 — Account-level Bulk Redirects (fallback)
# ===========================================================================

def list_bulk_redirect_lists(account_id: str) -> list[dict]:
    """
    List all "lists" in the account, then keep only the redirect-type ones.

    Cloudflare's Lists feature can store IP addresses, hostnames, ASNs, or
    redirects. Bulk Redirects use lists of kind == "redirect".

    API CALL:
        GET /accounts/{account_id}/rules/lists
    """
    data = _request("GET", f"/accounts/{account_id}/rules/lists")
    all_lists = data.get("result", []) or []

    # Filter down to redirect lists only.
    return [lst for lst in all_lists if lst.get("kind") == "redirect"]


def get_list_items(account_id: str, list_id: str) -> list[dict]:
    """
    Fetch every item inside one redirect list.

    Each item looks like:
        {
          "id": "....",
          "redirect": {
             "source_url": "old.example.com/path",
             "target_url": "https://new.example.com",
             "status_code": 301,
             ...other options...
          }
        }

    API CALL:
        GET /accounts/{account_id}/rules/lists/{list_id}/items

    NOTE on paging: large lists are paged with a cursor. For a beginner bot we
    fetch the first page (default 25). The README explains how to raise this if
    you have huge lists.
    """
    data = _request("GET", f"/accounts/{account_id}/rules/lists/{list_id}/items")
    return data.get("result", []) or []


def find_bulk_redirect_entry(account_id: str, domain: str
                             ) -> tuple[dict, dict, list[dict]] | None:
    """
    Search every redirect list in the account for an item whose source_url
    mentions the given domain.

    Parameters
    ----------
    account_id : str
    domain : str

    Returns
    -------
    (list_object, matching_item, all_items_in_that_list)
        if a match is found. We return the whole item list too, because
        updating one entry requires re-uploading the full list (see
        update_bulk_redirect_entry for why).
    None
        if no redirect list contains the domain.
    """
    for lst in list_bulk_redirect_lists(account_id):
        items = get_list_items(account_id, lst["id"])

        for item in items:
            source = item.get("redirect", {}).get("source_url", "")
            if domain.lower() in source.lower():
                return lst, item, items

    return None


def describe_bulk_item(item: dict) -> str:
    """Human-readable summary of one bulk-redirect entry for the chat."""
    redirect = item.get("redirect", {})
    return (
        f"<b>Source:</b> <code>{redirect.get('source_url', '')}</code>\n"
        f"<b>Current target:</b> <code>{redirect.get('target_url', '')}</code>\n"
        f"<b>Status code:</b> <code>{redirect.get('status_code', 301)}</code>"
    )


def update_bulk_redirect_entry(account_id: str, list_id: str,
                               all_items: list[dict], target_item_id: str,
                               new_target_url: str) -> str:
    """
    Change the target_url of ONE entry inside a bulk redirect list.

    WHY WE RE-UPLOAD THE WHOLE LIST:
        The Cloudflare Lists API has no "patch one item" endpoint. To change an
        item you replace the list's items with PUT. So we take every existing
        item, copy them unchanged EXCEPT the one we're editing (whose
        target_url we swap), and PUT them all back.

    This operation is ASYNCHRONOUS: Cloudflare returns an "operation_id" and
    processes the change in the background. We return that id; the caller polls
    get_bulk_operation_status to know when it's done.

    API CALL:
        PUT /accounts/{account_id}/rules/lists/{list_id}/items

    Returns
    -------
    str
        The operation_id to poll for completion.
    """
    # Rebuild the full payload of items. Each item we send must contain the
    # "redirect" object (Cloudflare assigns brand-new item ids on PUT).
    new_items = []
    for item in all_items:
        # Copy the existing redirect settings so we keep status_code etc.
        redirect = dict(item.get("redirect", {}))

        # If THIS is the item the user picked, swap its target URL.
        if item.get("id") == target_item_id:
            redirect["target_url"] = new_target_url

        new_items.append({"redirect": redirect})

    path = f"/accounts/{account_id}/rules/lists/{list_id}/items"
    data = _request("PUT", path, json=new_items)

    # The result of a PUT-items call contains the background operation id.
    return data.get("result", {}).get("operation_id", "")


def get_bulk_operation_status(account_id: str, operation_id: str) -> str:
    """
    Check whether a background Lists operation has finished.

    API CALL:
        GET /accounts/{account_id}/rules/lists/bulk_operations/{operation_id}

    Returns
    -------
    str
        One of: "pending", "running", "completed", "failed".
    """
    path = f"/accounts/{account_id}/rules/lists/bulk_operations/{operation_id}"
    data = _request("GET", path)
    return data.get("result", {}).get("status", "unknown")
