from __future__ import annotations

import re


_EMOJI_RE = re.compile(
    "["  # best-effort emoji detection (not perfect)
    "\U0001F300-\U0001FAFF"  # misc symbols & pictographs + extended
    "\u2600-\u27BF"  # dingbats / misc symbols
    "]+"
)


def lint_markdown(*, style_id: str, markdown: str) -> list[str]:
    require_mermaid = style_id.lower() in {"if.dave.v1.2", "dave", "if://bible/dave/v1.2"}
    if style_id.lower() in {
        "if.dave.v1",
        "if.dave.v1.1",
        "if.dave.v1.2",
        "dave",
        "if://bible/dave/v1.0",
        "if://bible/dave/v1.1",
        "if://bible/dave/v1.2",
    }:
        return _lint_dave(markdown, source_text=None, require_mermaid=require_mermaid)
    return [f"Unknown style id: {style_id}"]


def lint_markdown_with_source(*, style_id: str, markdown: str, source_text: str) -> list[str]:
    require_mermaid = style_id.lower() in {"if.dave.v1.2", "dave", "if://bible/dave/v1.2"}
    if style_id.lower() in {
        "if.dave.v1",
        "if.dave.v1.1",
        "if.dave.v1.2",
        "dave",
        "if://bible/dave/v1.0",
        "if://bible/dave/v1.1",
        "if://bible/dave/v1.2",
    }:
        return _lint_dave(markdown, source_text=source_text, require_mermaid=require_mermaid)
    return [f"Unknown style id: {style_id}"]


def _lint_dave(md: str, *, source_text: str | None, require_mermaid: bool) -> list[str]:
    issues: list[str] = []

    if "Standard Dave Footer" not in md:
        issues.append("Missing required footer: Standard Dave Footer")

    allowed_emojis = set(_EMOJI_RE.findall(source_text or ""))
    present_emojis = set(_EMOJI_RE.findall(md))
    disallowed = sorted(present_emojis - allowed_emojis)
    if disallowed:
        issues.append(
            "Contains emoji not present in source: " + " ".join(disallowed[:10]) + (" ..." if len(disallowed) > 10 else "")
        )

    if require_mermaid and "```mermaid" not in md:
        issues.append("Missing required Mermaid diagram")

    return issues
