#!/usr/bin/env python3
"""Static checks for ui-design HTML artifacts."""

from __future__ import annotations

import argparse
import json
import re
import sys
from dataclasses import dataclass
from pathlib import Path


PINNED_SCRIPTS = {
    "react": (
        "https://unpkg.com/react@18.3.1/umd/react.development.js",
        "sha384-hD6/rw4ppMLGNu3tX5cjIb+uRZ7UkRJ6BPkLpg4hAu/6onKUg4lLsHAs9EBPT82L",
    ),
    "react-dom": (
        "https://unpkg.com/react-dom@18.3.1/umd/react-dom.development.js",
        "sha384-u6aeetuaXnQ38mYT8rp6sbXaQe3NL9t+IBXmnYxwkUI2Hw4bsp2Wvmx4yRQF1uAm",
    ),
    "babel": (
        "https://unpkg.com/@babel/standalone@7.29.0/babel.min.js",
        "sha384-m08KidiNqLdpJqLq95G/LEi8Qvjl/xUYll3QILypMoQ65QorJ9Lvtp2RXYGBFj1y",
    ),
}


@dataclass
class Finding:
    severity: str
    message: str


def has_react_or_babel(content: str) -> bool:
    # 只认**真 React/Babel 件**的信号：text/babel 脚本、react/babel 的 CDN <script src>、或 React API 使用。
    # **不**靠正文里出现 "React"/"babel" 字样——讲技术栈的 deck 常把 "React + Next.js" 当**内容**写，
    # 过去子串匹配把它误判成 React 件、逼着补 pinned react 脚本（对静态 deck 是假的阻断 ERROR）。
    lowered = content.lower()
    if 'type="text/babel"' in lowered or "type='text/babel'" in lowered:
        return True
    if re.search(r"<script\b[^>]+src=[\"'][^\"']*(?:react|babel)[^\"']*[\"']", lowered):
        return True
    if re.search(r"\b(?:reactdom|react\.createelement|createroot)\b", lowered):
        return True
    return False


def check_pinned_scripts(content: str, findings: list[Finding]) -> None:
    if not has_react_or_babel(content):
        return
    for name, (src, integrity) in PINNED_SCRIPTS.items():
        if src not in content:
            findings.append(Finding("error", f"React/Babel artifact is missing pinned {name} script: {src}"))
        if integrity not in content:
            findings.append(Finding("error", f"React/Babel artifact is missing {name} integrity hash."))


def check_file_size(content: str, findings: list[Finding]) -> None:
    line_count = content.count("\n") + 1
    if line_count > 1000:
        findings.append(
            Finding(
                "warning",
                f"HTML artifact is {line_count} lines. Large prototypes should split CSS/JS/JSX or components.",
            )
        )


def check_react_babel_structure(content: str, findings: list[Finding]) -> None:
    if not has_react_or_babel(content):
        return

    if re.search(r"<script[^>]+type=[\"']module[\"']", content, re.I):
        findings.append(
            Finding(
                "warning",
                "React/Babel inline JSX artifacts should not mix in type=\"module\" scripts for helpers.",
            )
        )

    if re.search(r"\bconst\s+styles\s*=", content):
        findings.append(
            Finding(
                "warning",
                "Avoid global const styles = {}; it can collide with starter components or other scripts.",
            )
        )

    babel_count = len(re.findall(r"<script[^>]+type=[\"']text/babel[\"']", content, re.I))
    if babel_count > 1 and "Object.assign(window" not in content:
        findings.append(
            Finding(
                "warning",
                "Multiple text/babel scripts should expose shared components with Object.assign(window, ...).",
            )
        )


def check_tweaks(content: str, findings: list[Finding]) -> None:
    starts = list(re.finditer(r"/\*EDITMODE-BEGIN\*/", content))
    ends = list(re.finditer(r"/\*EDITMODE-END\*/", content))
    if not starts and not ends:
        findings.append(Finding("warning", "No Tweaks JSON block found. Add one when variants or live design controls are useful."))
        return
    if len(starts) != 1 or len(ends) != 1:
        findings.append(Finding("error", "Expected exactly one /*EDITMODE-BEGIN*/ ... /*EDITMODE-END*/ JSON block."))
        return
    if starts[0].end() > ends[0].start():
        findings.append(Finding("error", "Tweaks JSON markers are in the wrong order."))
        return
    raw_json = content[starts[0].end() : ends[0].start()].strip()
    try:
        json.loads(raw_json)
    except json.JSONDecodeError as exc:
        findings.append(Finding("error", f"Tweaks block is not valid JSON: {exc}"))

    if "__activate_edit_mode" not in content or "__deactivate_edit_mode" not in content:
        findings.append(Finding("warning", "Tweaks block exists, but edit-mode activate/deactivate listener was not found."))
    if "__edit_mode_available" not in content:
        findings.append(Finding("warning", "Tweaks block exists, but __edit_mode_available announcement was not found."))
    if "__edit_mode_set_keys" not in content:
        findings.append(Finding("warning", "Tweaks block exists, but __edit_mode_set_keys persistence was not found."))

    available_idx = content.find("__edit_mode_available")
    activate_idx = content.find("__activate_edit_mode")
    if available_idx != -1 and activate_idx != -1 and available_idx < activate_idx:
        findings.append(
            Finding(
                "warning",
                "Register the edit-mode message listener before announcing __edit_mode_available.",
            )
        )

    if "__edit_mode_set_keys" in content and not re.search(r"(\bedits\s*:|[\"']edits[\"'])", content):
        findings.append(
            Finding(
                "warning",
                "Tweaks persistence should prefer an edits payload; legacy keys payloads are only compatibility.",
            )
        )


def check_deck_and_fixed_size(content: str, findings: list[Finding], for_pptx_export: bool = False) -> None:
    looks_fixed_size = bool(re.search(r"\b(1920|1080|16:9|slide|deck|presentation|stage)\b", content, re.I))
    labels = re.findall(r'data-screen-label=["\']([^"\']+)["\']', content)
    if not labels:
        findings.append(Finding("warning", "No data-screen-label found. Label the main screen so preview feedback and screenshots can identify it."))
    if not looks_fixed_size:
        return
    # 「持久化当前页 / 视口缩放」是浏览器内交互观看的诉求。导出 PPTX 时 deck 是**静态导出目标**
    # （导出脚本自己控制每页 hidden、强制 1920×1080），这些 web-app 件不需要、也不该提示——
    # 否则诱导弱模型去补 localStorage/scale 而非修构图。
    if not for_pptx_export:
        if not re.search(r"localStorage|slideIndexChanged|activeSlide|currentSlide", content):
            findings.append(Finding("warning", "Slide/deck-like artifact should persist current slide or playback position."))
        if not re.search(r"transform\s*:\s*scale|style\.transform|scale\(", content):
            findings.append(Finding("warning", "Fixed-size artifact should include viewport scaling via transform: scale()."))
        if "transform-origin" not in content:
            findings.append(Finding("warning", "Fixed-size artifact should set transform-origin for stable viewport scaling."))

    if any(label.startswith("00 ") for label in labels):
        findings.append(Finding("warning", "Slide labels should be 1-indexed; verify labels do not start from 00."))
    if labels and not any(re.search(r"[\u4e00-\u9fff]", label) for label in labels):
        findings.append(Finding("warning", "Slide/screen labels should include Chinese titles, not only numeric or English labels."))

    if not for_pptx_export:
        stage_match = re.search(
            r"<main\b[^>]*(?:id|class)=[\"'][^\"']*scaled-stage[^\"']*[\"'][^>]*>.*?</main>",
            content,
            re.I | re.S,
        )
        if stage_match and "stage-controls" in stage_match.group(0):
            findings.append(Finding("warning", "Stage controls appear to be inside the scaled stage; keep controls outside scaled content."))

        looks_time_based = bool(
            re.search(r"\b(animation|video|timeline|play-toggle|isPlaying|currentTime|scrubber|播放)\b", content, re.I)
        )
        if looks_time_based and not re.search(r"localStorage|currentTime|isPlaying|playback|playing", content):
            findings.append(Finding("warning", "Animation/video-like artifacts should persist playback or time state."))


def check_speaker_notes(content: str, findings: list[Finding]) -> None:
    if re.search(r"id=[\"']speaker-notes[\"']", content, re.I) and "slideIndexChanged" not in content:
        findings.append(Finding("error", "speaker-notes are present but slideIndexChanged synchronization was not found."))


def check_placeholders(content: str, findings: list[Finding]) -> None:
    placeholder_patterns = [
        r"lorem ipsum",
        r"\bTODO\b",
        r"\bplaceholder\b",
        r"replace this",
        r"dummy (text|content|data)",
    ]
    for pattern in placeholder_patterns:
        if re.search(pattern, content, re.I):
            findings.append(Finding("warning", f"Possible unfinished placeholder content matched: {pattern}"))


def check_basic_html(content: str, findings: list[Finding]) -> None:
    lowered = content.lower()
    for tag in ("<!doctype html", "<html", "<head", "<body"):
        if tag not in lowered:
            findings.append(Finding("error", f"Missing basic HTML structure: {tag}"))
    if len(re.findall(r"<head\b", content, re.I)) > 1:
        findings.append(Finding("error", "Multiple <head> tags found. The HTML document is likely concatenated or malformed."))
    if len(re.findall(r"<body\b", content, re.I)) > 1:
        findings.append(Finding("error", "Multiple <body> tags found. The HTML document is likely concatenated or malformed."))
    if "<title" not in lowered:
        findings.append(Finding("warning", "Missing <title>."))
    if "name=\"viewport\"" not in lowered and "name='viewport'" not in lowered:
        findings.append(Finding("warning", "Missing viewport meta tag."))
    if not re.search(r"<html[^>]+lang=[\"']zh-CN[\"']", content, re.I):
        findings.append(Finding("warning", "Chinese ui-design artifacts should set <html lang=\"zh-CN\">."))


def mask_blocks_keep_newlines(content: str, pattern: str) -> str:
    def repl(match: re.Match[str]) -> str:
        text = match.group(0)
        return "".join("\n" if ch == "\n" else " " for ch in text)

    return re.sub(pattern, repl, content, flags=re.I | re.S)


def check_malformed_visible_css(content: str, findings: list[Finding]) -> None:
    masked = content
    for pattern in (
        r"<style\b[^>]*>.*?</style>",
        r"<script\b[^>]*>.*?</script>",
        r"<!--.*?-->",
    ):
        masked = mask_blocks_keep_newlines(masked, pattern)

    if re.search(r"^\s*/\*\s*=.{10,}", masked, re.M):
        findings.append(
            Finding(
                "error",
                "CSS comment block appears outside <style>. This will render as visible text and break PPTX export layers.",
            )
        )

    if re.search(r"^\s*(?:\.[A-Za-z_-][\w-]*|#[A-Za-z_-][\w-]*|[A-Za-z_-][\w-]*(?:\s+[.#A-Za-z_-]))[^{\n]{0,120}\{\s*$", masked, re.M):
        findings.append(
            Finding(
                "error",
                "CSS selector appears outside <style>. Wrap late CSS blocks in <style> before exporting.",
            )
        )


def check_visual_risks(content: str, findings: list[Finding]) -> None:
    if re.search(r"letter-spacing\s*:\s*-\d", content):
        findings.append(Finding("warning", "Avoid negative letter-spacing; it is especially risky for Chinese typography."))

    if re.search(r"font-size\s*:\s*clamp\([^;]*,\s*(?:8[4-9]|9\d|1\d\d)px\)", content):
        findings.append(Finding("warning", "Very large clamp() title size found. Chinese H1 should usually stay at or below 72-80px."))

    for match in re.finditer(r"font-size\s*:\s*(\d+(?:\.\d+)?)px", content):
        size = float(match.group(1))
        before = content[max(0, match.start() - 160):match.start()].lower()
        if size > 84 and ("h1" in before or "hero" in before or "title" in before):
            findings.append(Finding("warning", f"Very large title-like font-size found: {size:g}px. Check Chinese line breaks in screenshots."))
            break

    low_alpha_glass = re.findall(r"rgba\(\s*255\s*,\s*255\s*,\s*255\s*,\s*0\.(?:[0-5]\d?|59)\s*\)", content)
    if low_alpha_glass and ("backdrop-filter" in content or "glass" in content.lower()):
        findings.append(Finding("warning", "Low-opacity white glass surface found. Ensure text remains readable over gradients."))

    if "backdrop-filter" in content and not re.search(r"linear-gradient|radial-gradient", content):
        findings.append(Finding("warning", "Glass style uses backdrop-filter without gradients. Consider adding gradient light, edge highlights, and layer contrast."))

    if re.search(r"backdrop-filter", content) and len(re.findall(r"backdrop-filter", content)) >= 4:
        findings.append(Finding("warning", "Many backdrop-filter surfaces found. Ensure glass is not replacing structure, gradients, and readable hierarchy."))

    if re.search(r"(conic-gradient|linear-gradient|radial-gradient)", content) and re.search(
        r"rgba\(\s*255\s*,\s*255\s*,\s*255\s*,\s*0\.[0-6]", content
    ):
        findings.append(Finding("warning", "Gradient-heavy design with low-opacity white surfaces found. Confirm text contrast in browser screenshots."))

    if re.search(r"font-size\s*:\s*(?:[0-9](?:\.\d+)?px|1[0-1](?:\.\d+)?px|0\.[0-7]rem)", content):
        findings.append(Finding("warning", "Very small text size found. Chinese UI text below 12px is usually hard to read."))

    button_blocks = re.findall(r"(?:button|\.btn|\.cta)[^{]{0,80}\{[^}]+\}", content, re.I | re.S)
    if button_blocks:
        has_touch_size = any(re.search(r"(min-height|height)\s*:\s*(4[4-9]|[5-9]\d)px", block) for block in button_blocks)
        if not has_touch_size:
            findings.append(Finding("warning", "Button-like styles found without an obvious 44px min-height. Check mobile hit targets."))


OVERUSED_FONTS = ("inter", "roboto", "fraunces", "arial")


def check_overused_font(content: str, findings: list[Finding]) -> None:
    # 铁律「避免过度常见字体栈」（SKILL.md:119 / claude_design.md:255）此前只在 prose 层、无机械背书。
    # 这里只判 `font-family` 声明的**首个**字体族：CJK 栈把 Arial/Helvetica 列作**末位** Latin 兜底
    # 是合法实践（scaffold 默认栈即 PingFang…→Arial→sans-serif），故**不**因末位兜底误报——只有
    # Inter/Roboto/Fraunces 当**主字体**才是模板味。WARNING 级、不改 exit code（不硬拦弱模型）。
    for match in re.finditer(r"font-family\s*:\s*([^;}]+)", content, re.I):
        first = match.group(1).split(",")[0].strip().strip("'\"").lower()
        if first in OVERUSED_FONTS:
            findings.append(
                Finding(
                    "warning",
                    f"Overused font family as the primary typeface: '{first}'. Avoid Inter/Roboto/Fraunces as the leading font; commit to a brand or display face that carries the visual direction.",
                )
            )
            break


def check_left_border_accent(content: str, findings: list[Finding]) -> None:
    # 经典「左边框强调 + 圆角卡」是 claude_design.md:253 点名禁的 AI 味。确定性判定：**同一规则块内**
    # `border-left: <2–8px> solid <色>` 与 `border-radius` 共现 → WARNING（普通无圆角的左边框、或跨块
    # 各自出现都不报，避免误伤）。WARNING 级、不改 exit code。
    for block in re.finditer(r"\{([^{}]*)\}", content):
        body = block.group(1)
        if not re.search(r"border-radius\s*:", body, re.I):
            continue
        if re.search(r"border-left\s*:\s*[^;]*\b[2-8]px\s+solid\b", body, re.I):
            findings.append(
                Finding(
                    "warning",
                    "Left-border accent card detected (border-left <2-8px> solid + border-radius). Avoid the AI-slop left-accent rounded card; express emphasis through layout, type scale, or color roles instead.",
                )
            )
            break


def check_pptx_export_hints(content: str, findings: list[Finding]) -> None:
    # 三层分层现在由导出器 tagLayers **自动完成**（截图前按结构判：离散块→中层逐元素切图、文本→顶层
    # 可编辑框、其余→背景底图）。标注是可选 override，**不再是分层前提**——故**不**再为「没标
    # foreground/text」报警（那在自动分层后是假警报，会诱导模型做无谓标注、甚至把结构图当 AI 图）。
    # 这里只留**真有用**的两条：① 多页 deck 的 [hidden] CSS（预览稳定）；② 用 ignore 排除浏览器控件/装饰。
    if re.search(r"\.slide\s*\{[^}]*display\s*:\s*(?:grid|flex|block)", content, re.I | re.S):
        if not re.search(r"\[hidden\]\s*\{[^}]*display\s*:\s*none\s*!important", content, re.I | re.S):
            findings.append(
                Finding(
                    "warning",
                    "Slide CSS sets display, which can override the HTML hidden attribute. Add [hidden] { display: none !important; } for deck preview stability.",
                )
            )

    # 提示（info，非问题）：分层自动；要让某元素**保留烧进底图/不单独编辑**用 data-pptx-export="ignore"。
    if re.search(r"data-screen-label", content) and "data-pptx-export" not in content:
        findings.append(
            Finding(
                "info",
                "Layering is automatic (text → editable top layer, discrete blocks → per-element middle-layer images, the rest → background). No need to tag every element; use data-pptx-layer=\"foreground\" only to force a block, and data-pptx-export=\"ignore\" to keep browser controls / decorative art baked into the background.",
            )
        )


def check_gradient_over_image(content: str, findings: list[Finding]) -> None:
    # 真机头号事故：deck 写 `.edit-bg{background:<不透明渐变>, url('assets/img.png')}`——CSS 逗号分隔的
    # 多重背景里**靠前的层画在靠后的层之上**，故逗号在 url() 之前的渐变（尤其不透明）会把 AI 背景图整张盖死。
    # 确定性扫描 background/background-image 值中「渐变(linear/radial)在 url() 之前」的写法 → WARNING。
    # 渐变只应进**半透明** .edit-scrim 兜对比，不该和 url 图挤在同一个 background 简写里压在图上面。
    # WARNING 级、不阻断导出（exit code 不变）——与现有 PPTX 导出检查同风格。
    for match in re.finditer(
        r"background[^:]*:\s*[^;]*(?:linear|radial)-gradient[^;]*,\s*url\(",
        content,
        re.I,
    ):
        snippet = re.sub(r"\s+", " ", match.group(0).strip())
        if len(snippet) > 120:
            snippet = snippet[:120] + "…"
        findings.append(
            Finding(
                "warning",
                f"渐变写在 url 图之前会盖死背景图，渐变只应进半透明 .edit-scrim（命中：{snippet}）",
            )
        )


def run_checks(path: Path, for_pptx_export: bool = False, require_tweaks: bool = False) -> list[Finding]:
    findings: list[Finding] = []
    if not path.exists():
        return [Finding("error", f"File not found: {path}")]
    if not path.is_file():
        return [Finding("error", f"Path is not a file: {path}")]

    content = path.read_text(encoding="utf-8")
    check_basic_html(content, findings)
    check_malformed_visible_css(content, findings)
    if "scrollIntoView" in content:
        findings.append(Finding("error", "Do not use scrollIntoView in ui-design artifacts."))
    check_file_size(content, findings)
    check_pinned_scripts(content, findings)
    check_react_babel_structure(content, findings)
    # Tweaks/编辑模式是浏览器内「实时调参」功能；只有原型/变体页明确需要时才强制。
    has_tweaks_markers = "EDITMODE-BEGIN" in content or "EDITMODE-END" in content
    if (require_tweaks or has_tweaks_markers) and not for_pptx_export:
        check_tweaks(content, findings)
    check_deck_and_fixed_size(content, findings, for_pptx_export=for_pptx_export)
    check_speaker_notes(content, findings)
    check_placeholders(content, findings)
    check_visual_risks(content, findings)
    check_overused_font(content, findings)
    check_left_border_accent(content, findings)
    if for_pptx_export:
        check_pptx_export_hints(content, findings)
        check_gradient_over_image(content, findings)
    return findings


def parse_args() -> argparse.Namespace:
    parser = argparse.ArgumentParser(description=__doc__)
    parser.add_argument("html_file", help="HTML artifact to inspect.")
    parser.add_argument("--for-pptx-export", action="store_true", help="Show PPTX export layering and editability hints.")
    parser.add_argument("--require-tweaks", action="store_true", help="Require a valid EDITMODE/Tweaks block for prototype or variation artifacts.")
    parser.add_argument("--warnings-as-errors", action="store_true", help="Return non-zero when warnings are present.")
    return parser.parse_args()


def main() -> int:
    args = parse_args()
    findings = run_checks(Path(args.html_file), for_pptx_export=args.for_pptx_export, require_tweaks=args.require_tweaks)
    errors = [item for item in findings if item.severity == "error"]
    warnings = [item for item in findings if item.severity == "warning"]

    print(f"ui-design artifact check: {args.html_file}")
    if not findings:
        print("OK: no issues found.")
    else:
        for item in findings:
            print(f"{item.severity.upper()}: {item.message}")

    if errors or (args.warnings_as_errors and warnings):
        return 1
    return 0


if __name__ == "__main__":
    sys.exit(main())
