#!/usr/bin/env python3
"""扫描 Markdown 文件中的链接，校验外部 URL 可达性与本地文件引用有效性。
支持 --fix 自动修复可修复的断链，包括：
- file:/// 绝对路径转相对路径
- 相对路径层级自动校正（目录迁移后 ../ 层数不对的问题）
- 目录链接尾部斜杠补全
- 文件名重命名映射
- 加粗包裹的尖括号自动链接（**<url>**）规范化为标准链接 **[text](url)**
- 外部链接检查：HEAD 请求 + GET Range 回退、结果缓存、并发检测"""


# 版本校验：导入共享库
import sys as _sys
from pathlib import Path as _Path
_sys.path.insert(0, str(_Path(__file__).resolve().parent / "lib"))

from python310_version_check import enforce_python310

enforce_python310()

import argparse
import json
import os
import re
import sys
import time
import urllib.request
import urllib.error
import ssl
from dataclasses import dataclass
from datetime import datetime, timedelta
from functools import lru_cache
from pathlib import Path
from concurrent.futures import ThreadPoolExecutor, as_completed

from constants import (
    EXCLUDED_DIRS,
    LINK_CHECK_TIMEOUT,
    LINK_CHECK_WORKERS,
    LINK_CHECK_EXCLUDE_DIRS,
    LINK_CHECK_USER_AGENT,
)
from lib.project import resolve_project_root
from lib.link_fixer import is_code_fence_context, INLINE_LINK_RE
from lib.cli import add_common_args, setup_safe_output
from lib.markdown import (
    clear_tracked_index_cache,
    filter_test_fixture_paths,
    filter_untracked_paths,
    find_markdown_files,
    git_tracked_files,
    is_literal_path,
)
from lib.atomic_write import atomic_write_json
from lib.cache import get_cache_path, load_cache, save_cache
from lib import link_baseline

# 匹配引用式链接定义: [ref]: url
REF_LINK_RE = re.compile(r"^\s*\[([^\]]+)\]:\s*(.+)$", re.MULTILINE)
# 匹配引用式链接使用: [text][ref]
REF_USAGE_RE = re.compile(r"\[([^\]]*)\]\[([^\]]*)\]")
# 匹配加粗包裹的尖括号自动链接: **<url>**（如 **<https://example.com/>**）。
# 此类写法在部分 Markdown 渲染器与检查器中无法被识别为可点击/可校验的链接，
# 应在解析时纳入外部链接检查，并在 --fix 模式下规范化为 **[text](url)**。
BOLD_AUTOLINK_RE = re.compile(r"\*\*<([^>]+)>\*\*")


CURLY_PLACEHOLDER_RE = re.compile(r"\{[^}]+\}")
# 角括号占位段：`<域>`、`<bundle-id>` 这类 token 可能嵌在相对路径的某个
# 路径段里（如 `../../knowledge/<域>/<id>/index.md`），整串并非角括号目标。
# 字符类排除路径分隔符，避免把合法的 `<path/to/file.md>` 误判为占位符。
ANGLE_PLACEHOLDER_TOKEN_RE = re.compile(r"<[^<>/\\]+>")
# 路径扩展名：用于区分「真实文件引用」与「正文短语/表格单元」
PATH_EXTENSION_RE = re.compile(r"\.[A-Za-z0-9]{1,8}$")
# 中文正文特征：含中日韩字符的裸词几乎不可能是仓内路径
CJK_CHAR_RE = re.compile(r"[\u3400-\u4dbf\u4e00-\u9fff]")
# 正文标点：出现在裸词里说明是散文而不是路径
PROSE_PUNCTUATION = set("，。；：、！？（）「」【】《》…—·")

CACHE_DIR_NAME = ".agents/cache"
CACHE_FILE_NAME = "external-links-cache.json"
CACHE_TTL_DAYS = 7

EXTERNAL_URL_SUCCESS = 0
EXTERNAL_URL_BROKEN = 1
EXTERNAL_URL_SKIPPED = 2

# 链接检查跳过规则：这些路径在 .gitignore 中或为未初始化 submodule，
# 在 CI 中不存在但本地存在，不应报告为断链。
# 详见 .gitignore 与 .gitmodules（vendor/flexloop、vendor/ark-cli 为 submodule）。
LINK_CHECK_SKIP_SEGMENTS = (
    "/external/",
    "/playground/",
    "/.temp/",
    "/.agents/.cache/",
    "/.agents/cache/",
    "/.cache/",
    "/vendor/flexloop/",
    "/vendor/ark-cli/",
)

# 源码扫描跳过目录：这些目录装的不是本仓文档，而是本地语料/工具目录/缓存，
# 其内部 Markdown 的相对链接无法按本仓结构解析（实测贡献 1.4 万条假断链）。
# 与 LINK_CHECK_SKIP_SEGMENTS（按链接目标跳过）不同，这里按「源文件所在目录」
# 跳过，且只跳过未被 git 跟踪的文件——目录里一旦出现受版本控制的内容，照常检查。
# 免除资格由 lib.markdown.audit_skipped_paths 强制校验，违规直接抛错。
LINK_CHECK_UNTRACKED_SKIP_DIRS = frozenset({".corpus", ".workbuddy", ".cache"})

# 模板占位符：这些是文档模板中的示例链接，不是真实链接。
LINK_CHECK_PLACEHOLDER_EXACT = {"链接", "URL", "url", "<url>"}
LINK_CHECK_PLACEHOLDER_PREFIX = ("path/to/", "<!-- ", "{{", "占位符")


def _is_skipped_link_target(url: str) -> bool:
    """判断链接目标是否应跳过检查。

    跳过两类链接：
    1. 指向 .gitignore 排除路径或未初始化 submodule 的链接（CI 中不存在）
    2. 模板占位符链接（非真实链接）
    """
    if not url:
        return False
    clean = url.split("#")[0].strip()
    if not clean:
        return False

    # 模板占位符精确匹配
    if clean in LINK_CHECK_PLACEHOLDER_EXACT:
        return True
    # 模板占位符前缀匹配
    for prefix in LINK_CHECK_PLACEHOLDER_PREFIX:
        if clean.startswith(prefix):
            return True

    # 路径片段匹配（同时支持相对路径和 file:/// 绝对路径）
    normalized = clean.replace("\\", "/")
    for seg in LINK_CHECK_SKIP_SEGMENTS:
        if seg in normalized:
            return True
    return False


# 子模块未检出时无法校验目标是否存在，单独归为「无法判定」而非断链。
# 目录不存在（git clone 未 --recursive 时可能连目录都没有）与空目录（submodule
# 已注册但未 checkout）都属此类；而目录非空说明子模块已检出，此时目标缺失
# 就是真缺陷，必须照常报断链。
SUBMODULE_UNKNOWN_NOT_INITIALIZED = "子模块未初始化（目录不存在）"
SUBMODULE_UNKNOWN_EMPTY = "子模块未检出（空目录）"
SUBMODULE_SKIP_NOTE = "跳过校验"


@lru_cache(maxsize=8)
def _load_submodule_paths(project_root: str) -> tuple[str, ...]:
    """读取 .gitmodules 声明的子模块路径（仓库相对 posix，长路径优先）。"""
    gitmodules = Path(project_root) / ".gitmodules"
    try:
        content = gitmodules.read_text(encoding="utf-8")
    except OSError:
        return ()
    paths = set()
    for raw in re.findall(r"^\s*path\s*=\s*(.+)$", content, flags=re.MULTILINE):
        cleaned = raw.strip().strip('"').strip("'").strip("/").replace("\\", "/")
        if cleaned:
            paths.add(cleaned)
    # 长路径优先，保证嵌套子模块按最深一级判定
    return tuple(sorted(paths, key=len, reverse=True))


def submodule_check_state(target: Path, project_root: Path) -> str:
    """判断缺失目标是否落在「无法校验」的子模块内。

    返回:
      - "not_initialized": 子模块目录不存在
      - "empty": 子模块目录存在但为空（未检出）
      - "checked_out": 子模块已检出（目标缺失是真断链）
      - "outside": 目标不在任何子模块内（按普通断链处理）
    """
    try:
        root = project_root.resolve()
        rel = target.resolve().relative_to(root).as_posix()
    except (OSError, ValueError):
        return "outside"
    for sub in _load_submodule_paths(str(root)):
        if rel != sub and not rel.startswith(sub + "/"):
            continue
        sub_root = root / sub
        if not sub_root.exists():
            return "not_initialized"
        try:
            if not any(sub_root.iterdir()):
                return "empty"
        except OSError:
            # 无法列举时按已检出处理，宁可报断链也不要静默吞掉
            return "checked_out"
        return "checked_out"
    return "outside"


def _resolve_cache_path(project_root: Path) -> Path:
    """获取外部链接检查缓存文件路径。"""
    return get_cache_path(project_root, CACHE_FILE_NAME, CACHE_DIR_NAME)


def _links_load_cache(project_root: Path) -> dict:
    """加载外部链接检查缓存。"""
    return load_cache(_resolve_cache_path(project_root))


def _links_save_cache(project_root: Path, cache: dict):
    """保存外部链接检查缓存（原子写入，支持多进程并发）。"""
    save_cache(_resolve_cache_path(project_root), cache, CACHE_TTL_DAYS)


def is_cache_valid(entry: dict, ttl_days: int = CACHE_TTL_DAYS) -> bool:
    """判断缓存条目是否有效（未过期）。"""
    checked_at = entry.get("checked_at")
    if not checked_at:
        return False
    try:
        checked_time = datetime.fromisoformat(checked_at)
    except ValueError:
        return False
    return datetime.now() - checked_time < timedelta(days=ttl_days)


def is_template_placeholder(url: str) -> bool:
    """判断 URL 是否为模板占位符（如 <!-- ... -->、{变量名}、<占位符> 格式）。"""
    if url.startswith("<!--") and url.endswith("-->"):
        return True
    if CURLY_PLACEHOLDER_RE.search(url):
        return True
    # 尖括号占位符：<占位符>、<url> 这类模板示例。带路径分隔符或扩展名的
    # <path/to/file.md> 是合法的 Markdown 角括号目标，必须保留检查。
    if url.startswith("<") and url.endswith(">") and len(url) > 2:
        inner = url[1:-1].strip()
        if inner and "/" not in inner and "\\" not in inner and not PATH_EXTENSION_RE.search(inner):
            return True
        return False
    # 占位段嵌在相对路径中间（非整串角括号目标），同样不是可校验路径。
    if ANGLE_PLACEHOLDER_TOKEN_RE.search(url):
        return True
    return False


def is_non_path_reference(url: str) -> bool:
    """判断本地引用是否根本不是路径（正文短语 / 表格单元 / 裸词占位）。

    仅当引用「无路径分隔符、无扩展名、非锚点/绝对路径前缀」，且带正文特征
    （中文、空白或中文标点）时才判为非路径；`docs/`、`../guide`、`a.md`
    这类真实引用不受影响，避免把真断链一起过滤掉。
    """
    clean = url.split("#", 1)[0].split("?", 1)[0].strip()
    if not clean or clean in (".", ".."):
        return False
    if clean.startswith(("#", "/", "\\", "~", "file:", "mailto:", "http:", "https:")):
        return False
    if "/" in clean or "\\" in clean:
        return False
    if PATH_EXTENSION_RE.search(clean):
        return False
    if clean.startswith("<") and clean.endswith(">"):
        return True
    return (
        any(ch.isspace() for ch in clean)
        or bool(CJK_CHAR_RE.search(clean))
        or any(ch in PROSE_PUNCTUATION for ch in clean)
    )


def _strip_link_title(url: str) -> str:
    """从URL中剥离Markdown链接标题部分。

    Markdown链接支持可选标题：[text](url "title") / [text](url 'title') / [text](url (title))
    标题前必须有空格，且用引号或括号包裹。URL本身不应包含未编码空格，
    因此遇到第一个空格+引号/左括号时，截断为纯URL。
    """
    for quote in (' "', " '"):
        idx = url.find(quote)
        if idx > 0:
            return url[:idx]
    paren_idx = url.find(" (")
    if paren_idx > 0:
        return url[:paren_idx]
    return url


def _is_image_syntax(content: str, match_start: int) -> bool:
    """判断匹配位置是否是图片语法（!开头），即![alt](url)而非[text](url)。"""
    return match_start > 0 and content[match_start - 1] == "!"


def parse_links(file_path: Path) -> list[tuple[str, str, int]]:
    """解析 Markdown 文件中的链接，返回 (文本, URL, 行号) 列表。"""
    content = file_path.read_text(encoding="utf-8")
    links = []

    # 收集引用式链接定义（排除脚注 [^id]: ...）
    ref_defs = {}
    for m in REF_LINK_RE.finditer(content):
        ref_id = m.group(1)
        # 脚注定义以 ^ 开头，不是链接，跳过
        if ref_id.startswith("^"):
            continue
        ref_id = ref_id.lower()
        ref_url = m.group(2).strip()
        if not is_template_placeholder(ref_url):
            stripped = _strip_link_title(ref_url)
            if not is_non_path_reference(stripped):
                ref_defs[ref_id] = stripped

    # 解析内联链接
    for m in INLINE_LINK_RE.finditer(content):
        if is_code_fence_context(content, m.start()):
            continue
        if _is_image_syntax(content, m.start()):
            continue
        text = m.group(1)
        url = _strip_link_title(m.group(2).strip())
        if (
            url
            and not url.startswith("#")
            and not is_template_placeholder(url)
            and not is_non_path_reference(url)
        ):
            line_num = content[: m.start()].count("\n") + 1
            links.append((text, url, line_num))

    # 解析引用式链接使用 (不含定义行，排除脚注 [^id][^id] 模式)
    for m in REF_USAGE_RE.finditer(content):
        if is_code_fence_context(content, m.start()):
            continue
        if _is_image_syntax(content, m.start()):
            continue
        text = m.group(1)
        ref_id_raw = m.group(2).strip()
        # 脚注使用（任一 group 以 ^ 开头），跳过
        if text.startswith("^") or ref_id_raw.startswith("^"):
            continue
        ref_id = ref_id_raw.lower()
        if ref_id and ref_id in ref_defs:
            line_num = content[: m.start()].count("\n") + 1
            links.append((text, ref_defs[ref_id], line_num))

    # 解析加粗包裹的尖括号自动链接: **<url>**（如 **<https://example.com/>**）。
    # 这类写法等价于加粗的自动链接，应纳入外部链接检查。
    for m in BOLD_AUTOLINK_RE.finditer(content):
        if is_code_fence_context(content, m.start()):
            continue
        url = m.group(1).strip()
        if (
            url
            and not url.startswith("#")
            and not is_template_placeholder(url)
            and not is_non_path_reference(url)
        ):
            line_num = content[: m.start()].count("\n") + 1
            links.append((url, url, line_num))

    return links


def is_external_url(url: str) -> bool:
    """判断 URL 是否为外部链接。"""
    return url.startswith("http://") or url.startswith("https://")


def is_local_ref(url: str) -> bool:
    """判断 URL 是否为本地文件引用。"""
    return not is_external_url(url) and not url.startswith("#") and not url.startswith("mailto:")


def _make_request(url: str, method: str, timeout: int, ctx: ssl.SSLContext):
    """构造并发送 HTTP 请求。"""
    req = urllib.request.Request(url, method=method)
    req.add_header("User-Agent", LINK_CHECK_USER_AGENT)
    req.add_header("Accept", "*/*")
    if method == "GET":
        req.add_header("Range", "bytes=0-0")
    with urllib.request.urlopen(req, timeout=timeout, context=ctx) as resp:
        return resp.status, resp.geturl()


def check_external_link(url: str, timeout: int) -> tuple[str, int, str]:
    """检查外部链接是否可达。返回 (url, http_status, error_message)。

    检测策略：
    1. 首先使用 HEAD 请求（快速、不下载内容）
    2. HEAD 失败/不支持时，用 GET Range: bytes=0-0 回退（只获取第一个字节）
    3. 403/405 视为可接受（反爬虫/不支持 HEAD），但记录状态码
    """
    ctx = ssl.create_default_context()
    ctx.check_hostname = False
    ctx.verify_mode = ssl.CERT_NONE

    status = 0
    final_url = url
    error = ""

    for method in ("HEAD", "GET"):
        try:
            status, final_url = _make_request(url, method, timeout, ctx)
            if status < 400 or status in (403, 405):
                return (url, status, "")
            error = f"HTTP {status}"
        except urllib.error.HTTPError as e:
            status = e.code
            if e.code in (405, 403, 401):
                if method == "HEAD":
                    time.sleep(0.3)
                    continue
                return (url, e.code, "")
            error = str(e)
        except urllib.error.URLError as e:
            status = 0
            error = str(e.reason)
            if method == "HEAD":
                time.sleep(0.3)
                continue
        except Exception as e:
            status = 0
            error = str(e)
            if method == "HEAD":
                time.sleep(0.3)
                continue

    return (url, status, error)


def _find_bundle_root(fp: Path) -> Path | None:
    """向上查找最近一次出现过的 OKF bundle 根目录。

    OKF/bundle 约定（source-code-to-okf-wiki 工作流反模式4）：以 `/` 前缀的链接
    （如 `/concepts/00-overview.md`）表示**相对 bundle 根**的路径，而非文件系统根。
    bundle 根以「同时包含 index.md 与 log.md」为签名，从文件所在目录逐级向上
    查找最近的满足目录即返回；找不到返回 None。
    """
    cur = fp.resolve().parent
    for _ in range(16):  # 限制向上深度，防止极端路径耗尽
        if (cur / "log.md").exists() and (cur / "index.md").exists():
            return cur
        nxt = cur.parent
        if nxt == cur:  # 到达文件系统根
            break
        cur = nxt
    return None


def _resolve_local_target(
    fp: Path, ref: str, scan_root: Path | None = None
) -> Path:
    """解析本地文件引用为绝对路径，正确处理 `/` 前缀的 bundle-relative 路径。

    以 `/` 开头的引用优先解析到「最近的 bundle 根」；若未找到 bundle 根则回退到
    scan_root（--path 指定的扫描根）；两者均无时按旧行为解析到文件所在目录
    （Windows 上会被 pathlib 当作文件系统根，非 `/` 前缀引用不受影响）。
    """
    clean = ref.split("#")[0]
    if clean.startswith("/"):
        bundle_root = _find_bundle_root(fp)
        root = bundle_root or scan_root
        if root is not None:
            return (root / clean.lstrip("/")).resolve()
    return (fp.parent / clean).resolve()


def check_local_link(
    file_path: Path,
    url: str,
    scan_root: Path | None = None,
    project_root: Path | None = None,
) -> tuple[str, str, str]:
    """检查本地文件引用是否有效。返回 (url, status, message)。

    status:
      - "ok": 目标是文件，链接可正常打开
      - "directory": 目标是目录（IDE/Markdown渲染器无法直接打开目录，应链接到README.md）
      - "missing": 目标不存在（断链）
      - "unknown": 目标落在未检出的子模块内，无法判定；既不算断链也不入基线

    scan_root: 可选，--path 指定的扫描根目录；用于将 `/` 前缀的 bundle-relative
      链接解析到 bundle 根（无 bundle 根发现时的回退基准）。
    project_root: 可选，仓库根；提供时区分「子模块未检出（unknown）」与
      「子模块已检出但文件缺失（missing）」。
    """
    base_dir = file_path.parent
    clean_url = url.split("#")[0]
    if not clean_url:
        return (url, "ok", "")

    if clean_url.startswith("file:///"):
        from urllib.parse import urlparse, unquote
        parsed = urlparse(clean_url)
        p = unquote(parsed.path)
        # Windows 盘符形式 file:///D:/... → /D:/... → D:/...
        # POSIX 绝对路径 file:///media/... → /media/...（保留根斜杠，勿 lstrip 全部斜杠）
        if len(p) >= 3 and p[0] == "/" and p[2] == ":":
            p = p[1:]
        target = Path(p)
    else:
        target = _resolve_local_target(file_path, clean_url, scan_root)

    if not target.exists():
        # 跳过 .gitignore 排除路径、未初始化 submodule、模板占位符
        # （这些在 CI 中不存在但本地存在，或本就是非真实链接，不应报告为断链）
        if _is_skipped_link_target(url):
            return (url, "ok", "")
        if project_root is not None:
            state = submodule_check_state(target, project_root)
            if state == "not_initialized":
                return (url, "unknown", f"{SUBMODULE_UNKNOWN_NOT_INITIALIZED}，{SUBMODULE_SKIP_NOTE}: {target}")
            if state == "empty":
                return (url, "unknown", f"{SUBMODULE_UNKNOWN_EMPTY}，{SUBMODULE_SKIP_NOTE}: {target}")
        return (url, "missing", f"文件不存在: {target}")
    if target.is_dir():
        readme_candidate = target / "README.md"
        if readme_candidate.exists():
            return (url, "directory", f"链接到目录而非文件（应链接到 {target.name}/README.md）: {target}")
        return (url, "directory", f"链接到目录而非文件（目录内无README.md）: {target}")
    return (url, "ok", "")


# 只按「路径形态」校验的 frontmatter 字段。`source` 与 `related_*` 允许承载
# 散文式溯源描述（如「docs/xxx.md 第六章 ACT-5」「某文章 + 复盘洞察」
# 「multiplatform-video-publish（~/.workbuddy/skills/）」），这类值不是路径，
# 按路径校验只会制造噪声；但必须显式计数并在 --json 中单列，禁止静默丢弃。
PATH_FORM_ONLY_FIELDS = ("source",)
PATH_FORM_ONLY_PREFIXES = ("related_",)


def is_path_form_only_field(field_name: str) -> bool:
    """判断字段是否只按「路径形态」校验（路径形态仍严格照查，不做任何放宽）。"""
    return field_name in PATH_FORM_ONLY_FIELDS or field_name.startswith(PATH_FORM_ONLY_PREFIXES)


def is_path_form_value(value: str) -> bool:
    """判断 frontmatter 值是否具备路径形态。

    只审视锚点（`#`）之前的部分：`../x.md#中文锚点` 是路径引用，锚点里的中文
    不代表整串是散文；若把锚点一并纳入判断，这类真实路径会被误判为散文化而
    漏检。路径形态 = 无空白、无中日韩字符与全角标点、无多值分隔符（+ | , ;），
    且带扩展名或以 ./ ../ 开头。不满足者视为散文化描述，不按路径校验。
    """
    v = value.strip().strip('"').strip("'")
    if not v:
        return False
    head = v.split("#", 1)[0].strip()
    if not head:
        return False
    if any(ch.isspace() for ch in head):
        return False
    if CJK_CHAR_RE.search(head) or any(ch in PROSE_PUNCTUATION for ch in head):
        return False
    if head[0] in "（(「【":
        return False
    if re.search(r"[+|,;]", head):
        return False
    return bool(PATH_EXTENSION_RE.search(head)) or v.startswith("./") or v.startswith("../")


def _extract_paths_from_value(value: str) -> list[str]:
    """从字符串值中提取潜在的文件路径。

    处理多种source字段格式：
      - 单个路径: "path/to/file.md"
      - 路径+锚点: "path/to/file.md#section"
      - 多路径分隔: "path1.md + path2.md" 或 "path1.md, path2.md"
      - 路径+描述（旧格式）: "path/to/file.md + 复盘洞察 + 实践验证"（只提取路径部分）

    返回提取到的路径字符串列表。
    """
    if not value or not isinstance(value, str):
        return []
    v = value.strip().strip('"').strip("'")
    if not v:
        return []
    parts = re.split(r'\s*[+|,;]\s*', v)
    paths = []
    for part in parts:
        part = part.strip()
        if not part:
            continue
        if part.startswith(('http://', 'https://', '#', 'mailto:', 'session:', 'external:', 'spec:')):
            continue
        if '{{' in part or '}}' in part:
            continue
        if CURLY_PLACEHOLDER_RE.search(part):
            continue
        # 模板占位符（如 <sub-area>/<kebab-id>.toml）不是真实路径，不参与校验
        if ANGLE_PLACEHOLDER_TOKEN_RE.search(part):
            continue
        if re.search(r'[\u4e00-\u9fff]', part) and not ('.md' in part or '.toml' in part or '.py' in part):
            continue
        if '/' in part or '\\' in part or part.startswith('../') or part.startswith('./'):
            paths.append(part)
        elif re.search(r'\.(md|toml|py|js|ts|json|yaml|yml|sh|ps1)$', part, re.IGNORECASE):
            paths.append(part)
    return paths


def _is_path_value(value: str) -> bool:
    """判断字符串值是否包含需要验证的文件路径（向后兼容，使用_extract_paths_from_value）。"""
    return len(_extract_paths_from_value(value)) > 0


def _normalize_path_value(value: str) -> str:
    """清理路径值，去除引号和首尾空白。"""
    return value.strip().strip('"').strip("'")


def _check_single_path(
    md_path: Path,
    field_name: str,
    path_value: str,
    scan_root: Path | None = None,
    project_root: Path | None = None,
) -> tuple[Path, str, str, str] | None:
    """检查单个路径值是否有效。返回 (md_path, field_name, path_value, error_message) 或 None（通过）。

    project_root 提供时，落在未检出子模块内的缺失路径返回「跳过校验」标记，
    由 check_frontmatter_paths 归入跳过清单而不是断链。
    """
    v = _normalize_path_value(path_value)
    if not v:
        return None
    if v.startswith('docs/'):
        return (md_path, field_name, v, f"格式问题: 路径使用docs/绝对路径前缀，应使用相对路径")
    clean_path = v.split('#')[0]
    if not clean_path:
        return None
    target = _resolve_local_target(md_path, clean_path, scan_root)
    if not target.exists():
        # 跳过 .gitignore 排除路径、未初始化 submodule、模板占位符
        if _is_skipped_link_target(v):
            return None
        if project_root is not None:
            state = submodule_check_state(target, project_root)
            if state == "not_initialized":
                return (md_path, field_name, v, f"{SUBMODULE_UNKNOWN_NOT_INITIALIZED}，{SUBMODULE_SKIP_NOTE}: {target}")
            if state == "empty":
                return (md_path, field_name, v, f"{SUBMODULE_UNKNOWN_EMPTY}，{SUBMODULE_SKIP_NOTE}: {target}")
        return (md_path, field_name, v, f"文件不存在: {target}")
    if target.is_dir():
        readme_candidate = target / "README.md"
        if readme_candidate.exists():
            return (md_path, field_name, v, f"链接到目录而非文件（应指向{target.name}/README.md）: {target}")
        return (md_path, field_name, v, f"链接到目录而非文件（目录内无README.md）: {target}")
    return None


def check_frontmatter_paths(
    md_files: list[Path],
    fields: list[str] | None = None,
    check_related_fields: bool = True,
    scan_root: Path | None = None,
    project_root: Path | None = None,
    skipped: list[tuple[Path, str, str, str]] | None = None,
    prose_skipped: list[tuple[Path, str, str]] | None = None,
) -> list[tuple[Path, str, str, str]]:
    """校验 Markdown 文件 frontmatter 中包含路径的字段是否指向有效文件。

    通用的 frontmatter 路径检查机制，支持：
      - 显式指定的字段列表（默认: source, x-toml-ref）
      - 自动检测 related_ 前缀的字段（related_insights, related_patterns, parent_retrospective 等）
      - 字符串值和列表值（如 source: ["a.md", "b.md"]）
      - 多路径字符串（用 +、|、,、; 分隔的多个路径）
      - 路径+描述混合文本（如 "path/to/file.md + 复盘洞察"）
      - 自动跳过非路径值（URL、session:引用、占位符、纯ID、中文描述等）
      - 格式问题检测（docs/前缀绝对路径）

    返回:
      问题列表 [(md_path, field_name, path_value, error_message), ...]
    """
    from lib.frontmatter import parse_frontmatter_unified

    if fields is None:
        fields = ['source', 'x-toml-ref']

    broken = []
    for md_path in md_files:
        meta = parse_frontmatter_unified(md_path)
        if not meta:
            continue
        for field_name, value in meta.items():
            is_target_field = field_name in fields
            is_related_field = check_related_fields and field_name.startswith('related_')
            if not is_target_field and not is_related_field:
                continue
            values_to_check: list[str] = []
            if isinstance(value, str):
                raw_values = [value]
            elif isinstance(value, list):
                raw_values = [str(v) for v in value]
            else:
                raw_values = []
            for raw in raw_values:
                # source / related_* 允许散文化溯源描述，仅在路径形态时校验；
                # 跳过项必须计数上报，不得静默丢弃。
                if is_path_form_only_field(field_name) and not is_path_form_value(raw):
                    if prose_skipped is not None:
                        prose_skipped.append((md_path, field_name, raw.strip()))
                    continue
                values_to_check.extend(_extract_paths_from_value(raw))
            for v in values_to_check:
                result = _check_single_path(md_path, field_name, v, scan_root, project_root)
                if result:
                    if SUBMODULE_SKIP_NOTE in result[3]:
                        if skipped is not None:
                            skipped.append(result)
                        continue
                    broken.append(result)
    return broken


# ===== frontmatter 路径自动修复（--fix --check-frontmatter-paths）=====


@dataclass
class FrontmatterFix:
    """记录一次 frontmatter 路径字段的修复操作。"""
    file_path: Path
    field_name: str
    old_value: str
    new_value: str
    fix_type: str  # 'docs_prefix' | 'path_depth'
    reason: str = ""


def _relpath_posix(from_dir: Path, to_path: Path) -> str:
    """计算从 from_dir 到 to_path 的相对路径，输出 POSIX 格式（/ 分隔，含 ../）。"""
    rel = os.path.relpath(str(to_path.resolve()), str(from_dir.resolve()))
    return rel.replace("\\", "/")


def _classify_path_issue(error: str) -> str:
    """根据 _check_single_path 返回的错误信息分类问题类型。"""
    if "docs/绝对路径前缀" in error or "docs/前缀" in error:
        return "docs_prefix"
    if "文件不存在" in error:
        return "missing_file"
    if "链接到目录而非文件" in error:
        return "directory_link"
    return "unknown"


def _replace_path_in_text(text: str, old: str, new: str) -> str:
    """安全替换 frontmatter 文本中的路径字符串。

    使用正则前瞻断言确保只匹配完整路径（后跟锚点、引号、空白、列表结束符、
    分隔符或行尾），避免子串误伤（如 "../../foo.md" 误伤 "../../foo.md#section"
    或 "../foo.md.bak"）。

    自动处理 YAML 双引号字符串的转义：路径值在 YAML 双引号字符串中可能被转义
    （如 "d:\\\\AI\\\\docs\\\\..." 实际值为 "d:\\AI\\docs\\..."），
    因此同时尝试原始字符串和反斜杠转义后的字符串两种形式。
    """
    new_text = text

    # 尝试原始形式和 YAML 转义形式（\ → \\）
    candidates = [old]
    escaped_form = old.replace("\\", "\\\\")
    if escaped_form != old:
        candidates.append(escaped_form)

    for candidate in candidates:
        escaped_pattern = re.escape(candidate)
        pattern = escaped_pattern + r'(?=[#"\'\s\]\),|+;]|$)'
        new_text = re.sub(pattern, lambda m: new, new_text)

    return new_text


# 通用路径段集合：在路径关键词匹配验证中视为"无区分性"，跳过
_GENERIC_PATH_PARTS = {
    # 顶级目录
    "docs", "retrospective", "reports", "patterns", "assets",
    "knowledge", "operations", "methodology-patterns",
    # 报告分类目录
    "competitive-analysis", "project-reports", "task-reports",
    "insight-extraction", "external-learning", "tools-and-automation",
    "project-governance", "knowledge-content",
    # 模式分类目录
    "ai-collaboration", "spec-workflow", "tools-automation",
    "document-architecture", "product-growth",
    # 通用文件名（去 .md 后缀）
    "README", "index", "insight-extraction",
    "execution-retrospective", "retrospective-report",
    "export-suggestions", "insight-action-backlog",
    # 通用代码目录
    "skills", "libs", "src", "tests", "scripts",
    "actions", "insights",
    # 跨项目可能出现的顶级目录
    "AI", ".chaos",
    # 其他
    "SKILL", "SKILL.md",
}


def _verify_path_candidate(original_path: str, candidate: Path) -> bool:
    """验证搜索到的候选目标是否与原路径匹配。

    通过检查候选路径是否包含原路径的"有区分性"关键词，避免误匹配到同名
    但内容不同的文件（如多个 insight-extraction.md、多个 SKILL.md）。

    Args:
        original_path: 原始路径字符串（已解析的 YAML 值，单反斜杠）。
        candidate: find_target_by_stem 找到的候选目标。

    Returns:
        True 表示候选可信可修复，False 表示应跳过（避免误修）。
    """
    # 规范化为正斜杠，合并双反斜杠（YAML 转义残留）
    normalized = original_path.replace("\\\\", "/").replace("\\", "/")
    parts = [p for p in normalized.split("/") if p and p not in (".", "..")]
    if not parts:
        return True  # 原路径无有效段，信任 finder 评分

    # 提取有区分性的部分（跳过通用目录名、通用文件名、盘符、纯数字）
    distinctive_parts: list[str] = []
    for part in parts:
        stem = part[:-3] if part.endswith(".md") else part
        if stem in _GENERIC_PATH_PARTS or part in _GENERIC_PATH_PARTS:
            continue
        if part.isdigit() or stem.isdigit():
            continue
        if re.match(r"^[a-zA-Z]:$", part):  # 盘符如 d:
            continue
        distinctive_parts.append(part.lower())

    if not distinctive_parts:
        return True  # 原路径全是通用段，无法验证，信任 finder

    # 候选路径必须包含至少一个有区分性的部分
    candidate_str = str(candidate).lower().replace("\\", "/")
    for dp in distinctive_parts:
        if dp in candidate_str:
            return True

    return False


def _compute_frontmatter_fix(
    md_path: Path,
    old_path: str,
    project_root: Path,
    issue_type: str,
) -> str | None:
    """计算 frontmatter 路径字段的修复值。

    策略：
    - docs_prefix：将 docs/前缀路径解析为 (project_root / docs/...) 后计算相对路径
      若目标不存在，则降级为 find_target_by_stem 搜索 + 候选验证
    - directory_link：链接指向目录，若目录内有README.md则改为指向README.md
    - missing_file（路径深度错误或文件名变化）：用 find_target_by_stem 搜索目标，
      但必须通过候选验证（候选路径必须包含原路径的有区分性关键词）

    保留锚点（#section）。

    Args:
        md_path: 当前 Markdown 文件路径。
        old_path: 原始路径值（已解析的 YAML 值）。
        project_root: 项目根目录。
        issue_type: 问题类型（'docs_prefix' / 'missing_file' / 'directory_link' / 'unknown'）。

    Returns:
        修复后的路径字符串，或 None（无法安全修复时）。
    """
    from lib.link_fixer.finder import find_target_by_stem

    # 分离锚点
    anchor = ""
    clean_path = old_path
    if "#" in old_path:
        clean_path, anchor_part = old_path.split("#", 1)
        anchor = "#" + anchor_part

    # 处理 docs/ 前缀：直接从项目根解析（100% 安全的修复）
    if issue_type == "docs_prefix" and clean_path.startswith("docs/"):
        target = (project_root / clean_path).resolve()
        if target.exists():
            return _relpath_posix(md_path.parent, target) + anchor

    # 处理目录链接：若目录内有README.md，改为指向README.md
    if issue_type == "directory_link":
        dir_target = (md_path.parent / clean_path.rstrip("/")).resolve()
        readme_target = dir_target / "README.md"
        if readme_target.exists():
            base = clean_path.rstrip("/")
            return _relpath_posix(md_path.parent, readme_target) + anchor

    # 路径不存在：用文件名/目录名搜索目标
    target = find_target_by_stem(
        clean_path,
        project_root,
        near=md_path,
    )
    if target is None:
        return None

    # 候选验证：避免误匹配到同名但内容不同的文件
    if not _verify_path_candidate(clean_path, target):
        return None

    return _relpath_posix(md_path.parent, target) + anchor


def fix_frontmatter_paths(
    md_files: list[Path],
    project_root: Path,
    dry_run: bool = False,
) -> list[FrontmatterFix]:
    """修复 Markdown 文件 frontmatter 中的路径字段。

    可修复两类问题：
    - docs/ 前缀：转换为正确的相对路径（从 md_path.parent 到 project_root/docs/... 的相对路径）
    - 路径深度错误：通过 find_target_by_stem 搜索目标后计算正确相对路径

    不可修复的问题（跳过）：
    - x-toml-ref 指向不存在的 TOML 文件（需手动创建 TOML）
    - 搜索不到任何候选目标的路径

    修复范围仅限于 frontmatter 区域（--- ... --- 或 +++ ... +++ 之间），
    不影响正文中的链接。

    Args:
        md_files: 待修复的 Markdown 文件列表。
        project_root: 项目根目录（用于解析 docs/ 前缀路径和搜索目标文件）。
        dry_run: True=仅预览不写入文件，False=实际写入修复后的内容。

    Returns:
        修复记录列表，每条记录包含文件路径、字段名、原值、新值、修复类型。
    """
    from lib.frontmatter import (
        _YAML_FRONTMATTER_RE,
        _FRONTMATTER_RE,
        parse_frontmatter_unified,
    )

    target_fields = ["source", "x-toml-ref"]
    fixes: list[FrontmatterFix] = []

    for md_path in md_files:
        try:
            content = md_path.read_text(encoding="utf-8")
        except (OSError, UnicodeDecodeError):
            continue

        # 定位 frontmatter 文本范围（仅修复 frontmatter 内的路径）
        yaml_match = _YAML_FRONTMATTER_RE.match(content)
        toml_match = _FRONTMATTER_RE.match(content) if not yaml_match else None

        if yaml_match:
            fm_start = yaml_match.start(1)
            fm_end = yaml_match.end(1)
            fm_text = yaml_match.group(1)
        elif toml_match:
            fm_start = toml_match.start(1)
            fm_end = toml_match.end(1)
            fm_text = toml_match.group(1)
        else:
            continue

        # 解析合并后的元数据（含 x-toml-ref 加载的 TOML 字段）
        meta = parse_frontmatter_unified(md_path)
        if not meta:
            continue

        # 解析外部 TOML 文件路径（用于修复 TOML 中的 source 字段）
        toml_path: Path | None = None
        x_toml_ref_val = meta.get("x-toml-ref")
        if x_toml_ref_val and isinstance(x_toml_ref_val, str):
            toml_ref_clean = x_toml_ref_val.split("#")[0]
            resolved = (md_path.parent / toml_ref_clean).resolve()
            if resolved.exists():
                toml_path = resolved

        # 收集本文件所有需要修复的路径（field, old_value, new_value, fix_type, reason）
        file_fixes: list[tuple[str, str, str, str, str]] = []

        for field_name, value in meta.items():
            is_target = field_name in target_fields
            is_related = field_name.startswith("related_")
            if not is_target and not is_related:
                continue

            values_to_check: list[str] = []
            if isinstance(value, str):
                values_to_check.extend(_extract_paths_from_value(value))
            elif isinstance(value, list):
                for v in value:
                    values_to_check.extend(_extract_paths_from_value(str(v)))

            for v in values_to_check:
                result = _check_single_path(md_path, field_name, v)
                if not result:
                    continue  # 路径有效，跳过

                _, _, path_value, error = result
                issue_type = _classify_path_issue(error)

                # 跳过不可修复问题：x-toml-ref 指向不存在的 TOML 文件
                if field_name == "x-toml-ref" and issue_type == "missing_file":
                    continue

                new_path = _compute_frontmatter_fix(
                    md_path, path_value, project_root, issue_type
                )
                if new_path and new_path != path_value:
                    file_fixes.append((
                        field_name,
                        path_value,
                        new_path,
                        issue_type,
                        error.split(":")[0] if ":" in error else error,
                    ))

        if not file_fixes:
            continue

        # 在 frontmatter 文本范围内执行安全替换，并记录每条修复是否在 YAML 中生效
        new_fm_text = fm_text
        yaml_applied: list[bool] = []
        for field, old_v, new_v, fix_type, reason in file_fixes:
            before = new_fm_text
            new_fm_text = _replace_path_in_text(new_fm_text, old_v, new_v)
            yaml_applied.append(new_fm_text != before)

        # 重组文件内容（保留 frontmatter 标记 ---/+++）
        new_content = content[:fm_start] + new_fm_text + content[fm_end:]

        if not dry_run and new_content != content:
            md_path.write_text(new_content, encoding="utf-8", newline="")

        # 修复外部 TOML 文件中的路径（YAML 中未找到的字段回退写入 TOML）
        toml_pending = [
            (i, file_fixes[i])
            for i, applied in enumerate(yaml_applied)
            if not applied
        ]
        if toml_pending and toml_path and not dry_run:
            try:
                toml_content = toml_path.read_text(encoding="utf-8")
                new_toml_content = toml_content
                for _, (field, old_v, new_v, fix_type, reason) in toml_pending:
                    new_toml_content = _replace_path_in_text(
                        new_toml_content, old_v, new_v
                    )
                if new_toml_content != toml_content:
                    toml_path.write_text(
                        new_toml_content, encoding="utf-8", newline=""
                    )
            except (OSError, UnicodeDecodeError):
                pass

        for field, old_v, new_v, fix_type, reason in file_fixes:
            fixes.append(FrontmatterFix(
                file_path=md_path,
                field_name=field,
                old_value=old_v,
                new_value=new_v,
                fix_type=fix_type,
                reason=reason,
            ))

    return fixes


def print_frontmatter_fix_report(fixes: list[FrontmatterFix], dry_run: bool = False) -> None:
    """打印 frontmatter 路径修复报告。"""
    mode = "预览" if dry_run else "已修复"
    print(f"\n  frontmatter 路径修复（{mode}）: 共 {len(fixes)} 处")

    # 按文件分组统计
    by_file: dict[Path, list[FrontmatterFix]] = {}
    for fix in fixes:
        by_file.setdefault(fix.file_path, []).append(fix)

    # 按修复类型统计
    type_counts: dict[str, int] = {}
    for fix in fixes:
        type_counts[fix.fix_type] = type_counts.get(fix.fix_type, 0) + 1

    type_labels = {
        "docs_prefix": "docs/前缀转换",
        "path_depth": "路径深度校正",
        "missing_file": "路径深度校正",
        "directory_link": "目录→README.md",
        "unknown": "未知类型",
    }
    type_summary = ", ".join(
        f"{type_labels.get(t, t)}={c}" for t, c in type_counts.items()
    )
    print(f"  修复类型分布: {type_summary}")

    # 每个文件打印前 5 条修复，超出折叠
    for file_path, file_fixes in by_file.items():
        print(f"\n  [{file_path}] ({len(file_fixes)} 处)")
        for fix in file_fixes[:5]:
            print(f"    {fix.field_name}: {fix.old_value}")
            print(f"      → {fix.new_value}  ({fix.fix_type})")
        if len(file_fixes) > 5:
            print(f"    ... 其余 {len(file_fixes) - 5} 处省略")


def fix_bold_autolinks(md_files: list[Path], dry_run: bool = False) -> list[tuple[Path, int]]:
    """将加粗包裹的尖括号自动链接 **<url>** 规范化为标准 Markdown 链接 **[text](url)**。

    转换后可见文本仍为原 URL 内容（去除尖括号），因此不改变语义，仅使其成为
    可被 Markdown 渲染器与 check-links.py 正确识别与校验的可点击链接。

    Args:
        md_files: 待处理的 Markdown 文件列表。
        dry_run: True=仅预览不写入文件。

    Returns:
        修复记录列表 [(文件路径, 修复处数), ...]。
    """
    fixes: list[tuple[Path, int]] = []
    for md_path in md_files:
        try:
            content = md_path.read_text(encoding="utf-8")
        except (OSError, UnicodeDecodeError):
            continue

        parts: list[str] = []
        last = 0
        count = 0
        for m in BOLD_AUTOLINK_RE.finditer(content):
            if is_code_fence_context(content, m.start()):
                # 代码围栏内的文本原样保留，不修复
                parts.append(content[last:m.end()])
                last = m.end()
                continue
            url = m.group(1).strip()
            if not url or url.startswith("#") or is_template_placeholder(url):
                # 锚点/占位符不处理，原样保留
                parts.append(content[last:m.end()])
                last = m.end()
                continue
            parts.append(content[last:m.start()])
            parts.append(f"**[{url}]({url})**")
            last = m.end()
            count += 1

        if count == 0:
            continue
        parts.append(content[last:])
        new_content = "".join(parts)
        if not dry_run and new_content != content:
            md_path.write_text(new_content, encoding="utf-8", newline="")
        fixes.append((md_path, count))
    return fixes


def print_bold_autolink_report(fixes: list[tuple[Path, int]], dry_run: bool = False) -> None:
    """打印加粗自动链接规范化修复报告。"""
    mode = "预览" if dry_run else "已修复"
    total = sum(c for _, c in fixes)
    print(f"\n  加粗自动链接规范化（{mode}）: 共 {total} 处")
    for file_path, count in fixes:
        print(f"    {file_path}: {count} 处")


def main(argv=None) -> int:
    setup_safe_output()
    # 每次执行重新读取 git 索引：同一进程内多次调用（测试、更新基线后复扫）
    # 必须看到最新跟踪状态，否则新增文件会被当成未跟踪而漏检。
    clear_tracked_index_cache()
    parser = argparse.ArgumentParser(
        description="扫描 Markdown 文件中的链接，校验外部 URL 可达性与本地文件引用有效性。"
    )
    add_common_args(parser)
    parser.add_argument(
        "--paths",
        type=Path,
        nargs="+",
        default=None,
        help="指定多个目标目录（与 --path 互斥，支持批量扫描多个目录）",
    )
    parser.add_argument(
        "--check-external",
        action="store_true",
        default=False,
        help="同时检查外部 HTTP/HTTPS 链接（默认仅检查本地文件引用）",
    )
    parser.add_argument(
        "--check-frontmatter-paths",
        action="store_true",
        default=False,
        help="校验 frontmatter 中所有路径字段（source, x-toml-ref, related_*等）的有效性（推荐）",
    )
    parser.add_argument(
        "--check-x-toml-ref",
        action="store_true",
        default=False,
        help="[已废弃] 请使用 --check-frontmatter-paths，功能更全面",
    )
    parser.add_argument(
        "--timeout",
        type=int,
        default=LINK_CHECK_TIMEOUT,
        help="外部链接检查超时秒数（默认 10 秒）",
    )
    parser.add_argument(
        "--workers",
        type=int,
        default=LINK_CHECK_WORKERS,
        help="并发检查外部链接的线程数（默认 5）",
    )
    parser.add_argument(
        "--exclude",
        type=str,
        nargs="*",
        default=LINK_CHECK_EXCLUDE_DIRS,
        help="额外排除的目录名称（默认排除 docs/templates）",
    )
    parser.add_argument(
        "--fix",
        action="store_true",
        default=False,
        help="自动修复可修复的断链（绝对路径转相对路径、相对路径层级校正、目录斜杠补全等）",
    )
    parser.add_argument(
        "--dry-run",
        action="store_true",
        default=False,
        help="与 --fix 配合使用，仅预览修复内容不写入文件",
    )
    parser.add_argument(
        "--baseline",
        action="store_true",
        default=False,
        help="基线模式：只报告基线之外的新增断链（存量不打印）",
    )
    parser.add_argument(
        "--update-baseline",
        action="store_true",
        default=False,
        help="按当前断链重写基线文件（新增条目必须提供 --reason 或 --reason-map）",
    )
    parser.add_argument(
        "--reason",
        choices=link_baseline.REASON_ENUM,
        default=None,
        help="新增基线条目的原因（批量默认值）",
    )
    parser.add_argument(
        "--reason-map",
        type=str,
        default=None,
        help="逐条原因映射 JSON（数组，元素含 source/target/reason），优先于 --reason",
    )
    parser.add_argument(
        "--baseline-file",
        type=str,
        default=link_baseline.BASELINE_RELATIVE_PATH,
        help=f"基线文件路径（默认 {link_baseline.BASELINE_RELATIVE_PATH}）",
    )
    parser.add_argument(
        "--since",
        type=str,
        default=datetime.now().date().isoformat(),
        help="新增基线条目的入账日期（默认今天）",
    )
    parser.add_argument(
        "--review-by",
        type=str,
        default=None,
        help="新增基线条目的复核期限（默认 since + 90 天）",
    )
    parser.add_argument(
        "--rename",
        type=str,
        nargs="*",
        default=[],
        metavar="OLD=NEW",
        help="文件名重命名映射（用于文件迁移后修复引用），如 --rename 旧名.html=新名.html",
    )
    parser.add_argument(
        "--no-cache",
        action="store_true",
        default=False,
        help="外部链接检查时不使用缓存，强制重新请求所有 URL",
    )
    parser.add_argument(
        "--clear-cache",
        action="store_true",
        default=False,
        help="清除外部链接检查缓存后退出",
    )
    parser.add_argument(
        "--cache-ttl",
        type=int,
        default=CACHE_TTL_DAYS,
        help=f"外部链接缓存有效期天数（默认 {CACHE_TTL_DAYS} 天）",
    )
    args = parser.parse_args(argv)

    project_root = resolve_project_root(__file__)
    if args.paths and args.path:
        print("错误: --paths 与 --path 互斥，请仅使用其中一个", file=sys.stderr)
        return 1
    if args.paths:
        roots = list(args.paths)
    elif args.path:
        roots = [args.path]
    else:
        roots = [project_root]
    for r in roots:
        if not r.exists():
            print(f"错误: 路径不存在: {r}", file=sys.stderr)
            return 1

    if args.clear_cache:
        cache_path = _resolve_cache_path(project_root)
        if cache_path.exists():
            cache_path.unlink()
            print(f"已清除外部链接缓存: {cache_path}")
        else:
            print("无外部链接缓存文件，无需清除")
        return 0

    exclude_dirs = set(args.exclude)
    print("=" * 60)
    print("Markdown 链接校验")
    print("=" * 60)

    # 查找 Markdown 文件（支持多目录扫描）
    md_files = []
    file_root_map = {}  # 文件 -> 其所属扫描根目录（用于相对路径显示）
    dedup_index = {}  # 解析后实体 -> 在 md_files 中的下标（用于别名去重择优）
    explicit_files: set[Path] = set()  # --path 点名的单文件：不参与夹具跳过
    for root in roots:
        if root.is_file():
            # 单文件输入：直接纳入扫描。find_markdown_files 对文件路径
            # rglob 返回空，旧逻辑会以「找到 0 个文件…校验通过」假通过
            # 收场（2026-10-21 实测踩坑）。
            print(f"\n扫描文件: {root}")
            if root.suffix.lower() == ".md":
                resolved = root.resolve()
                if resolved not in file_root_map:
                    file_root_map[resolved] = root.parent
                    dedup_index[resolved] = len(md_files)
                    md_files.append(root)
                explicit_files.add(resolved)
                print("找到 1 个 Markdown 文件")
            else:
                print(
                    f"警告: 输入为非 .md 文件，无链接可校验: {root}",
                    file=sys.stderr,
                )
            continue
        print(f"\n扫描目录: {root}")
        if exclude_dirs:
            print(f"排除目录: {', '.join(sorted(exclude_dirs))}")
        root_md_files = find_markdown_files(root, exclude_dirs)
        print(f"找到 {len(root_md_files)} 个 Markdown 文件")
        for md_file in root_md_files:
            resolved = md_file.resolve()
            if resolved not in file_root_map:
                file_root_map[resolved] = root
                dedup_index[resolved] = len(md_files)
                md_files.append(md_file)
            elif is_literal_path(md_file) and not is_literal_path(
                md_files[dedup_index[resolved]]
            ):
                # 同一实体经联接/符号链接别名重复出现时，保留字面路径视图：
                # 否则别名视图会挤掉真实路径，跳过集一开就把真断链一起吞掉
                md_files[dedup_index[resolved]] = md_file
    print(f"\n合计: {len(md_files)} 个 Markdown 文件（已去重）")

    # 跳过未跟踪的本地语料/工具/缓存目录（硬约束由 audit_skipped_paths 校验）
    md_files, skip_stats = filter_untracked_paths(
        md_files, project_root, LINK_CHECK_UNTRACKED_SKIP_DIRS
    )
    if skip_stats:
        print(
            f"跳过未跟踪内容: {skip_stats['total']} 个 Markdown 文件"
            f"（未跟踪 {skip_stats.get('untracked', 0)}，"
            f"联接别名 {skip_stats.get('junction-alias', 0)}）"
        )
    # 跳过测试夹具数据（判据见 lib.markdown.is_test_fixture_markdown）
    md_files, fixture_skipped = filter_test_fixture_paths(
        md_files, project_root, explicit_files
    )
    if fixture_skipped:
        print(f"跳过测试夹具数据: {len(fixture_skipped)} 个 Markdown 文件")
        for fixture in fixture_skipped:
            try:
                shown = fixture.relative_to(project_root).as_posix()
            except ValueError:
                shown = str(fixture)
            print(f"  - {shown}")
    if not md_files:
        # 零对象扫描必须显式告警：通过语义只属于「检查过且无断链」，
        # 不属于「什么都没检查」。
        print(
            "警告: 未扫描到任何 Markdown 文件，请确认 --path 指向的目录或 .md 文件",
            file=sys.stderr,
        )

    # 自动修复（--fix）
    rename_map = {}
    for mapping in args.rename:
        if "=" in mapping:
            old, new = mapping.split("=", 1)
            rename_map[old] = new

    if args.fix:
        from lib.link_fixer import fix_directory_links, print_fix_report, _infer_project_root
        dry_run = args.dry_run
        mode_str = "预览修复（dry-run）" if dry_run else "自动修复"
        print(f"\n0. {mode_str}...")
        for root in roots:
            inferred_root = _infer_project_root(root)
            fixes = fix_directory_links(
                root, inferred_root,
                rename_map=rename_map or None,
                dry_run=dry_run,
                exclude_dirs=exclude_dirs,
            )
            if fixes:
                print_fix_report(fixes, dry_run=dry_run)
            else:
                print(f"  {root}: 未发现需要修复的断链。")

        # frontmatter 路径字段自动修复（需配合 --check-frontmatter-paths 触发）
        if args.check_frontmatter_paths or args.check_x_toml_ref:
            print(f"\n0.1 {mode_str} frontmatter 路径字段...")
            inferred_root = _infer_project_root(roots[0]) if roots else project_root
            fm_fixes = fix_frontmatter_paths(md_files, inferred_root, dry_run=dry_run)
            if fm_fixes:
                print_frontmatter_fix_report(fm_fixes, dry_run=dry_run)
            else:
                print("  未发现可自动修复的 frontmatter 路径问题。")

        # 加粗包裹的尖括号自动链接规范化（**<url>** → **[text](url)**）
        print(f"\n0.2 {mode_str} 加粗自动链接规范化...")
        ba_fixes = fix_bold_autolinks(md_files, dry_run=dry_run)
        if ba_fixes:
            print_bold_autolink_report(ba_fixes, dry_run=dry_run)
        else:
            print("  未发现需要规范化的加粗自动链接。")

    # 解析所有链接
    all_links: list[tuple[Path, str, str, int]] = []  # (文件, 文本, URL, 行号)
    unreadable = 0
    for md_file in md_files:
        try:
            links = parse_links(md_file)
        except OSError as exc:
            # 权限受限/IO 异常的文件（如本地工作区中的只读文件）不应导致全量扫描崩溃
            unreadable += 1
            print(f"  警告: 无法读取 {md_file}（{exc.__class__.__name__}），已跳过")
            continue
        for text, url, line_num in links:
            all_links.append((md_file, text, url, line_num))
    if unreadable:
        print(f"  跳过不可读文件: {unreadable} 个")

    # 分类链接
    external_links = [(f, t, u, ln) for f, t, u, ln in all_links if is_external_url(u)]
    local_links = [(f, t, u, ln) for f, t, u, ln in all_links if is_local_ref(u)]
    other_links = [(f, t, u, ln) for f, t, u, ln in all_links if not is_external_url(u) and not is_local_ref(u)]

    print(f"  内联链接: {len(all_links)}")
    print(f"  外部链接: {len(external_links)}")
    print(f"  本地引用: {len(local_links)}")
    print(f"  其他链接: {len(other_links)}（锚点/mailto 等）")

    # 检查本地文件引用
    broken_local = []
    warning_local = []
    unknown_local: list[tuple[Path, int, str, str, str]] = []
    baseline_hits: list[tuple[str, str]] = []  # (仓库相对源文件, 断链目标)
    print(f"\n1. 检查本地文件引用（共 {len(local_links)} 个）...")
    for file_path, text, url, line_num in local_links:
        file_root = file_root_map.get(file_path.resolve(), roots[0])
        url_str, status, message = check_local_link(
            file_path, url, scan_root=file_root, project_root=project_root
        )
        if status == "missing":
            file_root = file_root_map.get(file_path.resolve(), roots[0])
            rel_path = file_path.relative_to(file_root) if file_root in file_path.parents else file_path
            broken_local.append((rel_path, line_num, text, url_str, message))
            try:
                source_rel = file_path.resolve().relative_to(project_root.resolve())
            except ValueError:
                source_rel = None
            if source_rel is not None:
                baseline_hits.append((source_rel.as_posix(), url_str, "link"))
        elif status == "directory":
            file_root = file_root_map.get(file_path.resolve(), roots[0])
            rel_path = file_path.relative_to(file_root) if file_root in file_path.parents else file_path
            warning_local.append((rel_path, line_num, text, url_str, message))
        elif status == "unknown":
            file_root = file_root_map.get(file_path.resolve(), roots[0])
            rel_path = file_path.relative_to(file_root) if file_root in file_path.parents else file_path
            unknown_local.append((rel_path, line_num, text, url_str, message))

    if unknown_local:
        not_initialized = sum(
            1 for item in unknown_local if item[4].startswith(SUBMODULE_UNKNOWN_NOT_INITIALIZED)
        )
        empty = len(unknown_local) - not_initialized
        print(
            f"  跳过 {len(unknown_local)} 条子模块链接（未检出）:"
            f" 目录不存在 {not_initialized}，空目录 {empty}"
        )
        print("    这些链接无法判定有效性，既不算断链也不入基线；"
              "全量校验需 git submodule update --init --recursive")

    # 检查 frontmatter 路径字段（在基线之前完成，使 frontmatter 断链也能入账）
    broken_frontmatter = []
    skipped_frontmatter: list[tuple[Path, str, str, str]] = []
    prose_skipped_frontmatter: list[tuple[Path, str, str]] = []
    check_fm = args.check_frontmatter_paths or args.check_x_toml_ref
    if check_fm:
        if args.check_x_toml_ref and not args.check_frontmatter_paths:
            print("   注意: --check-x-toml-ref 已废弃，自动升级为 --check-frontmatter-paths（检查source/x-toml-ref/related_*等所有路径字段）")
        broken_frontmatter = check_frontmatter_paths(
            md_files,
            scan_root=roots[0] if len(roots) == 1 else None,
            project_root=project_root,
            skipped=skipped_frontmatter,
            prose_skipped=prose_skipped_frontmatter,
        )
        if prose_skipped_frontmatter:
            fields_note = "/".join(
                sorted({row[1] for row in prose_skipped_frontmatter})
            )
            print(
                f"   跳过 {len(prose_skipped_frontmatter)} 条散文化 {fields_note}"
                f"（非路径形态，未按路径校验）；明细见 --json 的 prose_skipped_frontmatter"
            )
        if skipped_frontmatter:
            print(
                f"   跳过 {len(skipped_frontmatter)} 条子模块路径（未检出）:"
                " 无法判定有效性，不计入断链"
            )

    # ---- 基线模式 ----------------------------------------------------------
    # 指纹只认（仓库相对源文件, 规范化目标），不含行号；只允许全仓扫描，
    # 避免用子集算出错误的仓库相对路径或误清空基线。
    baseline_summary = None
    if args.baseline or args.update_baseline:
        baseline_path = Path(args.baseline_file)
        if not baseline_path.is_absolute():
            baseline_path = Path(project_root) / baseline_path
        tracked = git_tracked_files(project_root)
        if tracked is None:
            print("错误: 基线模式需要可用的 git 索引来验证源文件", file=sys.stderr)
            return 1
        scope_ok = (
            len(roots) == 1
            and Path(roots[0]).resolve() == Path(project_root).resolve()
        )
        if not scope_ok:
            print(
                "错误: 基线的 source 以仓库根为基准，只允许全仓扫描"
                "（请去掉 --path/--paths）",
                file=sys.stderr,
            )
            return 1
        current_counts: dict[tuple[str, str, str], int] = {}
        untracked_ignored = 0
        for md_path, field_name, ref, _error in broken_frontmatter:
            try:
                source_rel = md_path.resolve().relative_to(Path(project_root).resolve()).as_posix()
            except (OSError, ValueError):
                continue
            baseline_hits.append((source_rel, ref, "frontmatter"))
        for source_rel, url, kind in baseline_hits:
            # 基线只收 git 跟踪的源文件：未跟踪文件在 CI 中不存在，
            # 既不能入账，也不能在 --baseline 下制造永久“新增”。
            if source_rel not in tracked:
                untracked_ignored += 1
                continue
            key = link_baseline.fingerprint(source_rel, url, kind)
            current_counts[key] = current_counts.get(key, 0) + 1
        if args.update_baseline:
            try:
                existing = link_baseline.load_baseline(baseline_path, tracked)
                reason_map = (
                    link_baseline.load_reason_map(Path(args.reason_map))
                    if args.reason_map
                    else None
                )
                merged, stats = link_baseline.build_updated_entries(
                    current_counts,
                    existing,
                    reason=args.reason,
                    reason_map=reason_map,
                    since=args.since,
                    review_by=args.review_by,
                )
                link_baseline.save_baseline(baseline_path, merged, tracked)
            except link_baseline.BaselineError as exc:
                print(f"错误: {exc}", file=sys.stderr)
                return 1
            print(f"\n基线已更新: {baseline_path}")
            print(
                f"  新增 {stats['added']}，保留 {stats['kept']}，"
                f"重分类 {stats['reclassified']}，"
                f"清理已消失 {stats['stale']}，总计 {stats['total']}"
            )
            if untracked_ignored:
                print(f"  忽略未跟踪源文件的断链 {untracked_ignored} 条（不入基线）")
            if unknown_local:
                print(f"  跳过 {len(unknown_local)} 条子模块链接（未检出），不计入基线")
            return 0
        try:
            baseline = link_baseline.load_baseline(baseline_path, tracked)
        except link_baseline.BaselineError as exc:
            print(f"错误: {exc}", file=sys.stderr)
            return 1
        fresh, stale = link_baseline.diff_baseline(current_counts, baseline)
        fresh_keys = {(source, target, kind) for source, target, kind, _, _ in fresh}
        broken_local = [
            row
            for row in broken_local
            if link_baseline.normalize_source(str(row[0])) in tracked
            and link_baseline.fingerprint(str(row[0]), row[3], "link") in fresh_keys
        ]
        kept_frontmatter = []
        for row in broken_frontmatter:
            md_path, field_name, ref, error = row
            try:
                source_rel = md_path.resolve().relative_to(Path(project_root).resolve()).as_posix()
            except (OSError, ValueError):
                kept_frontmatter.append(row)
                continue
            if (
                source_rel in tracked
                and link_baseline.fingerprint(source_rel, ref, "frontmatter") in fresh_keys
            ):
                kept_frontmatter.append(row)
        broken_frontmatter = kept_frontmatter
        baseline_summary = {
            "current": len(current_counts),
            "known": len(baseline),
            "new": len(fresh),
            "stale": stale,
            "untracked_ignored": untracked_ignored,
        }
        print(
            f"\n[基线] 当前断链指纹 {len(current_counts)} 条，基线内 {len(baseline)} 条；"
            f"新增 {len(fresh)} 条，基线中已消失 {stale} 条"
        )
        if untracked_ignored:
            print(f"  忽略未跟踪源文件的断链 {untracked_ignored} 条（不入基线）")
        if unknown_local:
            print(f"  跳过 {len(unknown_local)} 条子模块链接（未检出），不计入基线")

    if broken_local:
        print(f"   失败: {len(broken_local)} 个断链")
        for rel_path, line_num, text, url, error in broken_local:
            print(f"     [{rel_path}:{line_num}] {text} -> {url} ({error})")
    else:
        if baseline_summary:
            print(
                f"   通过: 无基线外新增断链"
                f"（基线内 {baseline_summary['known']} 条存量）"
            )
        else:
            print(f"   通过: 所有本地引用均存在")

    if warning_local:
        print(f"   警告: {len(warning_local)} 个链接指向目录（IDE无法直接打开，建议链接到README.md）")
        for rel_path, line_num, text, url, msg in warning_local:
            print(f"     [{rel_path}:{line_num}] {text} -> {url} ({msg})")

    # 检查外部链接（可选）
    broken_external = []
    cached_results = {}
    urls_to_check = set()

    if args.check_external and external_links:
        unique_urls = set(u for _, _, u, _ in external_links)
        print(f"\n2. 检查外部链接（共 {len(unique_urls)} 个唯一 URL，超时 {args.timeout}s）...")

        cache = _links_load_cache(project_root) if not args.no_cache else {}
        cache.pop("_metadata", None)

        for url in unique_urls:
            entry = cache.get(url)
            if entry and is_cache_valid(entry, args.cache_ttl) and not args.no_cache:
                cached_results[url] = (entry.get("status", 0), entry.get("error", ""))
            else:
                urls_to_check.add(url)

        cached_count = len(cached_results)
        if cached_count > 0:
            print(f"   使用缓存结果: {cached_count} 个（TTL {args.cache_ttl} 天），需重新检查: {len(urls_to_check)} 个")

        url_results = dict(cached_results)
        if urls_to_check:
            with ThreadPoolExecutor(max_workers=args.workers) as executor:
                futures = {executor.submit(check_external_link, url, args.timeout): url for url in urls_to_check}
                for future in as_completed(futures):
                    url, status, error = future.result()
                    url_results[url] = (status, error)
                    cache[url] = {
                        "status": status,
                        "error": error,
                        "checked_at": datetime.now().isoformat(),
                        "ok": status > 0 and (status < 400 or status in (403, 405)),
                    }

            if not args.no_cache:
                _links_save_cache(project_root, cache)

        for file_path, text, url, line_num in external_links:
            status, error = url_results.get(url, (0, "未检查"))
            if status == 0 or (status >= 400 and status not in (403, 405, 401)):
                file_root = file_root_map.get(file_path.resolve(), roots[0])
                rel_path = file_path.relative_to(file_root) if file_root in file_path.parents else file_path
                broken_external.append((rel_path, line_num, text, url, status, error))

        if broken_external:
            ok_count = len(unique_urls) - len(set(u for _, _, u, _, _, _ in broken_external))
            print(f"   可达: {ok_count}，不可达: {len(broken_external)}")
            for rel_path, line_num, text, url, status, error in broken_external:
                print(f"     [{rel_path}:{line_num}] {text} -> {url} (HTTP {status}: {error})")
        else:
            print(f"   通过: 所有外部链接均可达")
    elif not args.check_external:
        print(f"\n2. 跳过外部链接检查（使用 --check-external 启用）")
        print(f"   共 {len(external_links)} 个外部链接待检查")

    # frontmatter 结果已在基线之前计算，这里只负责报告
    if check_fm:
        print(f"\n3. frontmatter 路径字段: 共 {len(md_files)} 个文件")
        if broken_frontmatter:
            print(f"   失败: {len(broken_frontmatter)} 个 frontmatter 路径问题")
            for md_path, field_name, ref, error in broken_frontmatter:
                file_root = file_root_map.get(md_path.resolve(), roots[0])
                try:
                    rel_path = md_path.relative_to(file_root) if file_root in file_root_map and file_root in md_path.parents else md_path
                except ValueError:
                    rel_path = md_path
                print(f"     [{rel_path}] {field_name}: {ref} ({error})")
        else:
            print(f"\n   通过: 所有 frontmatter 路径字段均有效")

    # JSON 输出
    if args.json:
        result = {
            "summary": {
                "total_files": len(md_files),
                "total_links": len(all_links),
                "external_links": len(external_links),
                "local_links": len(local_links),
                "other_links": len(other_links),
                "broken_local": len(broken_local),
                "unknown_local": len(unknown_local),
                "warning_local": len(warning_local),
                "broken_external": len(broken_external),
                "broken_frontmatter": len(broken_frontmatter),
                "unknown_frontmatter": len(skipped_frontmatter),
                "prose_skipped_frontmatter": len(prose_skipped_frontmatter),
            },
            "baseline": baseline_summary,
            "broken_local": [
                {
                    "file": str(f),
                    "line": ln,
                    "text": t,
                    "url": u,
                    "error": e,
                }
                for f, ln, t, u, e in broken_local
            ],
            "warning_local": [
                {
                    "file": str(f),
                    "line": ln,
                    "text": t,
                    "url": u,
                    "warning": w,
                }
                for f, ln, t, u, w in warning_local
            ],
            "broken_external": [
                {
                    "file": str(f),
                    "line": ln,
                    "text": t,
                    "url": u,
                    "status": s,
                    "error": e,
                }
                for f, ln, t, u, s, e in broken_external
            ],
            "broken_frontmatter": [
                {
                    "file": str(f),
                    "field": field,
                    "value": v,
                    "error": e,
                }
                for f, field, v, e in broken_frontmatter
            ],
            "prose_skipped_frontmatter": [
                {
                    "file": str(f),
                    "field": field,
                    "value": v,
                }
                for f, field, v in prose_skipped_frontmatter
            ],
        }
        print("\n" + json.dumps(result, ensure_ascii=False, indent=2))

    # 汇总
    print("\n" + "=" * 60)
    total_broken = len(broken_local) + len(broken_external) + len(broken_frontmatter)
    total_warnings = len(warning_local)
    total_unknown = len(unknown_local) + len(skipped_frontmatter)
    unknown_note = (
        f"（跳过 {total_unknown} 条未检出子模块链接，未参与校验）" if total_unknown else ""
    )
    if prose_skipped_frontmatter:
        unknown_note += (
            f"（跳过 {len(prose_skipped_frontmatter)} 条散文化 frontmatter 溯源描述，未按路径校验）"
        )
    if total_broken == 0:
        if total_warnings == 0:
            print(f"校验通过: 所有链接均有效{unknown_note}")
        else:
            print(f"校验通过（有 {total_warnings} 个警告）: 无断链，但存在目录链接建议修复{unknown_note}")
        print("=" * 60)
        return 0
    else:
        parts = [f"本地 {len(broken_local)}", f"外部 {len(broken_external)}"]
        if check_fm:
            parts.append(f"frontmatter {len(broken_frontmatter)}")
        if total_warnings > 0:
            parts.append(f"目录链接警告 {total_warnings}")
        print(f"校验失败: 发现 {total_broken} 个断链（{', '.join(parts)}）")
        print("=" * 60)
        return 1


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