import re
import sys
from pathlib import Path


def check(text):
    expected = ["商品信息", "标题", "三条卖点", "商品正文", "发布前核对"]
    headings = list(re.finditer(r"^## (.+?)\s*$", text, re.MULTILINE))
    errors = []
    if [match.group(1) for match in headings] != expected:
        return ["二级标题缺失、增加或顺序不符合五节模板。"]
    sections = {}
    for index, match in enumerate(headings):
        end = headings[index + 1].start() if index + 1 < len(headings) else len(text)
        sections[match.group(1)] = text[match.end():end].strip()
    for field in ["商品名", "材质", "外部尺寸", "使用场景", "价格"]:
        if not re.search(r"^- " + re.escape(field) + r"：\S.*$", sections["商品信息"], re.MULTILINE):
            errors.append("商品信息缺少非空字段：" + field)
    title_lines = [line for line in sections["标题"].splitlines() if line.strip()]
    if len(title_lines) != 1:
        errors.append("标题应为一行非空文案。")
    selling_lines = [line for line in sections["三条卖点"].splitlines() if line.strip()]
    if len(selling_lines) != 3 or any(not re.match(r"^- \S", line) for line in selling_lines):
        errors.append("卖点应为恰好三条非空 Markdown 列表项。")
    body = sections["商品正文"]
    if not body or re.search(r"\n\s*\n", body):
        errors.append("商品正文应为一段非空文案。")
    review_lines = [line for line in sections["发布前核对"].splitlines() if line.strip()]
    if not review_lines or any(not re.match(r"^- \S", line) for line in review_lines):
        errors.append("发布前核对应为非空 Markdown 清单。")
    if "```" in text:
        errors.append("请保存 Markdown 正文，移除包裹文案的代码围栏。")
    if re.search(r"\[[^\]\n]+\]", text):
        errors.append("仍有方括号模板占位符；请填入资料或明确写未提供。")
    return errors


def main():
    if len(sys.argv) != 2:
        print("用法：python3 check-copy.py 文案文件.md", file=sys.stderr)
        return 2
    try:
        text = Path(sys.argv[1]).read_text(encoding="utf-8")
    except (OSError, UnicodeError) as error:
        print("读取失败：" + str(error), file=sys.stderr)
        return 2
    errors = check(text)
    if errors:
        for error in errors:
            print("STRUCTURE_ERROR: " + error, file=sys.stderr)
        return 1
    print("STRUCTURE_OK：仅证明 Markdown 结构符合模板，商品事实仍需人工核实。")
    return 0


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