"""
📦 Delimiters advanced add-ons for Telethon
👤 Created by Ankit Chaubey | https://github.com/ankit-chaubey/delimiters
© 2026 Ankit Chaubey. All rights reserved.
📬 Contact: m.ankitchaubey@gmail.com | Telegram: @ankify @AnkitChaubey @ChaubeyBot
⚠️ Warning: Do not edit this file unless you are absolutely sure what you are doing.
💥 Changing this file may break the package.
🚀 Initially built for personal use, now released publicly.

# =====================================================

Phase 1: parse / unparse (pure, offline, reversible)
Phase 2: resolve_mentions (async, network, send-time only)
"""

from typing import Iterable, Tuple, List
import re

from telethon.tl.types import (
    TypeMessageEntity,
    MessageEntityTextUrl,
    MessageEntityUrl,
    InputMessageEntityMentionName,
)

from .custom_markdown import CustomMarkdown
from .html_ext import CustomHtmlParser


# =====================================================
# CONSTANTS
# =====================================================

_MENTION_RE = re.compile(r"^tg://user\?id=(\d+)$")


# =====================================================
# PHASE 2: MENTION RESOLVER (FINAL STEP)
# =====================================================

async def resolve_mentions(
    client,
    text: str,
    entities: List[TypeMessageEntity],
) -> List[TypeMessageEntity]:
    """
    Upgrade tg://user URLs into real mention entities.

    ⚠️ MUST be called only immediately before send_message().
    ⚠️ Parsing / round-trips must be completed before this.
    """
    resolved: List[TypeMessageEntity] = []

    for e in entities:
        url = None

        # Markdown & Html parser path
        if isinstance(e, MessageEntityTextUrl):
            url = e.url

        if url:
            m = _MENTION_RE.match(url)
            if m:
                uid = int(m.group(1))
                try:
                    input_user = await client.get_input_entity(uid)
                    resolved.append(
                        InputMessageEntityMentionName(
                            e.offset,
                            e.length,
                            input_user,
                        )
                    )
                    continue
                except Exception:
                    # Fail safely: keep original entity
                    pass

        resolved.append(e)

    return resolved


# =====================================================
# PHASE 1: PURE PARSING API (OFFLINE SAFE)
# =====================================================

def parse(
    text: str,
    *,
    mode: str = "md",
) -> Tuple[str, List[TypeMessageEntity]]:
    """
    Parse Markdown or HTML into (text, entities).

    ✔ Offline
    ✔ Deterministic
    ✔ Round-trip safe
    ✔ Does NOT resolve mentions
    """
    if not text:
        return text, []

    mode = mode.lower()

    if mode in ("md", "markdown"):
        return CustomMarkdown.parse(text)

    if mode == "html":
        return CustomHtmlParser.parse(text)

    raise ValueError(f"Unknown parse mode: {mode!r}")


def unparse(
    text: str,
    entities: Iterable[TypeMessageEntity],
    *,
    mode: str = "md",
) -> str:
    """
    Convert entities back into Markdown or HTML.

    ✔ Reversible
    ✔ tg://user preserved
    ✔ Safe for multiple conversions
    """
    if not text:
        return text

    mode = mode.lower()

    if mode in ("md", "markdown"):
        return CustomMarkdown.unparse(text, entities)

    if mode == "html":
        return CustomHtmlParser.unparse(text, entities)

    raise ValueError(f"Unknown unparse mode: {mode!r}")

# ===============================
# HTML -> Mention (fixed) V0.1.3
# ===============================
