"""
bot_logic.py
============

PURPOSE
-------
This is the "brain" of the bot. It receives a parsed Telegram update and
decides what to do, orchestrating the Telegram and Cloudflare helper modules
and remembering where each user is via the state store.

THE CONVERSATION FLOW (matches your spec)
-----------------------------------------
  /start
      -> greeting + instructions.

  user sends a domain (e.g. "example.com")
      1. Find the Zone ID.
      2. Look for a ZONE-LEVEL single redirect that mentions the domain.
            found -> show it, remember it, ask for the new target URL.
      3. If none, fall back to ACCOUNT-LEVEL bulk redirect lists.
            found -> show it, remember it, ask for the new target URL.
      4. If still nothing -> tell the user, no redirect to edit.

  user sends a new URL
      -> validate it, show a Confirm/Cancel inline keyboard.

  user taps Confirm
      -> apply the change via the right Cloudflare endpoint, report result.
  user taps Cancel
      -> discard, clear state.

STATE "step" VALUES WE USE
--------------------------
  "awaiting_url"     : we showed a redirect, now waiting for the new URL text.
  "awaiting_confirm" : user gave a URL, waiting for Confirm/Cancel tap.
"""

import logging

import cloudflare_api as cf
import telegram_api as tg
from cloudflare_api import CloudflareError
from config import CLOUDFLARE_ACCOUNT_ID
import state

log = logging.getLogger(__name__)


# ---------------------------------------------------------------------------
# Small helpers
# ---------------------------------------------------------------------------

def _looks_like_domain(text: str) -> bool:
    """
    Very light check: does this text look like a bare domain (has a dot, no
    spaces, no scheme)? We keep it simple on purpose — Cloudflare will reject
    anything truly invalid anyway.
    """
    text = text.strip()
    return (
        "." in text
        and " " not in text
        and not text.startswith("http://")
        and not text.startswith("https://")
    )


def _looks_like_url(text: str) -> bool:
    """A new target URL must start with http:// or https://."""
    text = text.strip().lower()
    return text.startswith("http://") or text.startswith("https://")


# ---------------------------------------------------------------------------
# Entry point — called by app.py for every incoming update
# ---------------------------------------------------------------------------

def handle_update(update: dict) -> None:
    """
    Top-level router. A Telegram "update" can be many things; we only care
    about two:
      - a normal text "message"
      - a "callback_query" (an inline-keyboard button tap)

    Parameters
    ----------
    update : dict
        The raw JSON Telegram POSTed to our webhook, already parsed to a dict.
    """
    try:
        if "message" in update:
            _handle_message(update["message"])
        elif "callback_query" in update:
            _handle_callback(update["callback_query"])
        # Any other update type (edited messages, etc.) we simply ignore.
    except CloudflareError as exc:
        # A clean, expected error from Cloudflare — tell the user nicely.
        chat_id = _extract_chat_id(update)
        if chat_id:
            tg.send_message(chat_id, f"⚠️ Cloudflare error: {exc}")
    except Exception:
        # Unexpected bug. Log the full traceback for debugging, and apologise.
        log.exception("Unhandled error while processing update")
        chat_id = _extract_chat_id(update)
        if chat_id:
            tg.send_message(chat_id, "❌ Something went wrong. Please try again.")


def _extract_chat_id(update: dict) -> int | None:
    """Pull the chat id out of whatever kind of update this is (for errors)."""
    if "message" in update:
        return update["message"]["chat"]["id"]
    if "callback_query" in update:
        return update["callback_query"]["message"]["chat"]["id"]
    return None


# ---------------------------------------------------------------------------
# Handling plain text messages
# ---------------------------------------------------------------------------

def _handle_message(message: dict) -> None:
    """
    Process a text message. We branch on:
      - commands (/start, /cancel)
      - whether the user is mid-conversation (awaiting a URL)
      - otherwise treat the text as a domain to search.
    """
    chat_id = message["chat"]["id"]

    # Some messages (photos, stickers) have no "text". Ignore those.
    text = message.get("text", "").strip()
    if not text:
        tg.send_message(chat_id, "Please send a domain name as text.")
        return

    # --- Commands ---------------------------------------------------------
    if text == "/start" or text == "/help":
        _send_welcome(chat_id)
        return

    if text == "/cancel":
        state.clear_state(chat_id)
        tg.send_message(chat_id, "✅ Cancelled. Send a domain to start again.")
        return

    # --- Mid-conversation: are we waiting for a new URL from this user? ----
    current = state.get_state(chat_id)
    if current and current["step"] == "awaiting_url":
        _handle_new_url(chat_id, text, current["data"])
        return

    # --- Otherwise treat the text as a domain to look up ------------------
    if _looks_like_domain(text):
        _search_domain(chat_id, text)
    else:
        tg.send_message(
            chat_id,
            "I didn't understand that.\n\n"
            "Send a <b>domain name</b> like <code>example.com</code> to begin, "
            "or /help for instructions.",
        )


def _send_welcome(chat_id: int) -> None:
    """Send the greeting / usage instructions."""
    tg.send_message(
        chat_id,
        "👋 <b>Cloudflare Redirect Manager</b>\n\n"
        "Send me a <b>domain name</b> (e.g. <code>example.com</code>) and I'll "
        "look up its redirect rule on Cloudflare.\n\n"
        "• First I check the domain's <b>Single Redirects</b> (zone level).\n"
        "• If none match, I check your account's <b>Bulk Redirect Lists</b>.\n\n"
        "When I find one, I'll show you its current target and let you set a "
        "new one.\n\n"
        "Type /cancel anytime to start over.",
    )


# ---------------------------------------------------------------------------
# Step: search a domain
# ---------------------------------------------------------------------------

def _search_domain(chat_id: int, domain: str) -> None:
    """
    Implements steps 1–3 of the workflow: find the zone, check zone-level
    single redirects, then fall back to account-level bulk redirects.
    """
    tg.send_message(chat_id, f"🔎 Looking up <code>{domain}</code> on Cloudflare…")

    # --- Step 1: Zone ID --------------------------------------------------
    zone_id = cf.get_zone_id(domain)
    if not zone_id:
        tg.send_message(
            chat_id,
            f"❌ I couldn't find a Cloudflare zone for <code>{domain}</code>.\n"
            "Make sure the domain is in this Cloudflare account and spelled "
            "correctly (no http://, no trailing slash).",
        )
        return

    # --- Step 2: Zone-level Single Redirect -------------------------------
    zone_match = cf.find_zone_redirect_rule(zone_id, domain)
    if zone_match:
        ruleset_id, rule = zone_match

        # Remember everything we need to update this rule later.
        state.set_state(chat_id, "awaiting_url", {
            "mode": "zone_redirect",
            "domain": domain,
            "zone_id": zone_id,
            "ruleset_id": ruleset_id,
            "rule": rule,             # store the whole rule so we can PATCH it
        })

        tg.send_message(
            chat_id,
            "✅ <b>Found a Single Redirect (zone level)</b>\n\n"
            f"{cf.describe_zone_rule(rule)}\n\n"
            "➡️ Send me the <b>new target URL</b> "
            "(must start with http:// or https://).",
        )
        return

    # --- Step 3: Account-level Bulk Redirect fallback ---------------------
    tg.send_message(
        chat_id,
        "No zone-level redirect matched. Checking account Bulk Redirect lists…",
    )

    bulk_match = cf.find_bulk_redirect_entry(CLOUDFLARE_ACCOUNT_ID, domain)
    if bulk_match:
        lst, item, all_items = bulk_match

        state.set_state(chat_id, "awaiting_url", {
            "mode": "bulk_redirect",
            "domain": domain,
            "list_id": lst["id"],
            "list_name": lst.get("name", ""),
            "item_id": item["id"],
            "all_items": all_items,    # needed to re-upload the whole list
        })

        tg.send_message(
            chat_id,
            f"✅ <b>Found a Bulk Redirect entry</b> in list "
            f"<code>{lst.get('name', '')}</code>\n\n"
            f"{cf.describe_bulk_item(item)}\n\n"
            "➡️ Send me the <b>new target URL</b> "
            "(must start with http:// or https://).",
        )
        return

    # --- Nothing found anywhere -------------------------------------------
    state.clear_state(chat_id)
    tg.send_message(
        chat_id,
        f"😕 I found the zone for <code>{domain}</code>, but no matching "
        "redirect in either Single Redirects or Bulk Redirect lists.\n\n"
        "There's nothing for me to edit. Double-check that a redirect actually "
        "exists for this domain.",
    )


# ---------------------------------------------------------------------------
# Step: user supplied a new URL -> ask for confirmation
# ---------------------------------------------------------------------------

def _handle_new_url(chat_id: int, new_url: str, data: dict) -> None:
    """
    The user sent what should be the new target URL. Validate it and, if good,
    show a Confirm/Cancel inline keyboard before we touch Cloudflare.
    """
    new_url = new_url.strip()

    if not _looks_like_url(new_url):
        tg.send_message(
            chat_id,
            "⚠️ That doesn't look like a valid URL. It must start with "
            "<code>http://</code> or <code>https://</code>. Try again, or "
            "/cancel.",
        )
        return

    # Stash the pending URL alongside the existing context and move to the
    # confirmation step.
    data["pending_url"] = new_url
    state.set_state(chat_id, "awaiting_confirm", data)

    # Build a short summary of what's about to change.
    if data["mode"] == "zone_redirect":
        what = (f"the <b>Single Redirect</b> for "
                f"<code>{data['domain']}</code>")
    else:
        what = (f"the <b>Bulk Redirect</b> entry for "
                f"<code>{data['domain']}</code>")

    # The inline keyboard sends back callback_data "confirm" or "cancel".
    keyboard = tg.inline_keyboard([
        [("✅ Confirm", "confirm"), ("❌ Cancel", "cancel")],
    ])

    tg.send_message(
        chat_id,
        f"You want to point {what} to:\n\n"
        f"<code>{new_url}</code>\n\n"
        "Apply this change?",
        reply_markup=keyboard,
    )


# ---------------------------------------------------------------------------
# Handling inline-keyboard button taps (Confirm / Cancel)
# ---------------------------------------------------------------------------

def _handle_callback(callback: dict) -> None:
    """
    A button was tapped. callback["data"] is the callback_data we set on the
    button ("confirm" or "cancel").
    """
    callback_id = callback["id"]
    chat_id = callback["message"]["chat"]["id"]
    message_id = callback["message"]["message_id"]
    choice = callback.get("data", "")

    # ALWAYS answer the callback first to stop the button's spinner.
    tg.answer_callback_query(callback_id)

    current = state.get_state(chat_id)

    # If state expired or is missing, the buttons are stale.
    if not current or current["step"] != "awaiting_confirm":
        tg.edit_message_text(
            chat_id, message_id,
            "⌛ This request expired. Please send the domain again.",
        )
        state.clear_state(chat_id)
        return

    data = current["data"]

    if choice == "cancel":
        state.clear_state(chat_id)
        tg.edit_message_text(chat_id, message_id, "❌ Change cancelled.")
        return

    if choice == "confirm":
        # Replace the buttons with a "working…" note so the user gets feedback.
        tg.edit_message_text(chat_id, message_id, "⏳ Applying change…")
        _apply_change(chat_id, message_id, data)
        return


# ---------------------------------------------------------------------------
# Step: actually apply the confirmed change to Cloudflare
# ---------------------------------------------------------------------------

def _apply_change(chat_id: int, message_id: int, data: dict) -> None:
    """
    Perform the real update against Cloudflare, depending on which mode we are
    in, then report the outcome and clear the conversation state.
    """
    new_url = data["pending_url"]

    try:
        if data["mode"] == "zone_redirect":
            # Update the single-redirect rule in place.
            cf.update_zone_redirect_rule(
                zone_id=data["zone_id"],
                ruleset_id=data["ruleset_id"],
                rule=data["rule"],
                new_target_url=new_url,
            )
            tg.edit_message_text(
                chat_id, message_id,
                f"✅ <b>Done!</b> The Single Redirect for "
                f"<code>{data['domain']}</code> now points to:\n"
                f"<code>{new_url}</code>",
            )

        elif data["mode"] == "bulk_redirect":
            # Re-upload the list with the one entry changed. This returns an
            # async operation id we then poll a few times.
            operation_id = cf.update_bulk_redirect_entry(
                account_id=CLOUDFLARE_ACCOUNT_ID,
                list_id=data["list_id"],
                all_items=data["all_items"],
                target_item_id=data["item_id"],
                new_target_url=new_url,
            )
            _report_bulk_result(chat_id, message_id, data, new_url, operation_id)

    except CloudflareError as exc:
        tg.edit_message_text(
            chat_id, message_id,
            f"⚠️ Cloudflare refused the update:\n<code>{exc}</code>",
        )

    finally:
        # Whether it worked or not, this conversation is over.
        state.clear_state(chat_id)


def _report_bulk_result(chat_id: int, message_id: int, data: dict,
                        new_url: str, operation_id: str) -> None:
    """
    Bulk-list updates are asynchronous. We poll the operation status a handful
    of times (these usually finish within a couple of seconds). We avoid long
    sleeps so the webhook responds quickly.
    """
    import time  # local import: only needed here.

    if not operation_id:
        # Some Cloudflare responses complete instantly without an id.
        tg.edit_message_text(
            chat_id, message_id,
            f"✅ Submitted. The Bulk Redirect for <code>{data['domain']}</code> "
            f"should now point to <code>{new_url}</code>.",
        )
        return

    status = "pending"
    # Poll up to ~6 seconds total (3 tries x 2s). Plenty for normal lists.
    for _ in range(3):
        status = cf.get_bulk_operation_status(CLOUDFLARE_ACCOUNT_ID, operation_id)
        if status in ("completed", "failed"):
            break
        time.sleep(2)

    if status == "completed":
        tg.edit_message_text(
            chat_id, message_id,
            f"✅ <b>Done!</b> The Bulk Redirect entry for "
            f"<code>{data['domain']}</code> now points to:\n"
            f"<code>{new_url}</code>",
        )
    elif status == "failed":
        tg.edit_message_text(
            chat_id, message_id,
            "⚠️ Cloudflare reported the bulk update <b>failed</b>. "
            "Check the Cloudflare dashboard.",
        )
    else:
        # Still running — tell the user it's in progress.
        tg.edit_message_text(
            chat_id, message_id,
            f"⏳ Submitted. Cloudflare is still applying the change for "
            f"<code>{data['domain']}</code> → <code>{new_url}</code>. "
            "It should take effect shortly.",
        )
