"""构建机生产端发布流水线(爬取 + NPU 向量化 → points/*.parquet + manifest.json → GitCode)。

替代旧 refresh.py(双 cron 分裂、62 万 .md 入仓、6335 临时 Qdrant):
- 数据仓(starmountain/ascend-rag-data)只分发 manifest.json(普通 git)与
  points/<repo>/<lang>.parquet(LFS,行按 ID 排序字节可复现),不再存 corpus/ 原始 .md;
- 爬取先写入 staging 目录(硬链接播种现有语料),通过「总文件数 + 逐 source/repo 整仓」
  缩库熔断后才原子切入活语料目录,失败绝不污染本地语料与下轮基线;
- 向量化直接由 src.ingest.export_corpus_points 产出确定性 parquet(复用 EmbedCache),
  不需要起临时 6335 Qdrant 进程;
- 所有 scope 未变化时零提交零推送(幂等);有实质更新时压为单提交快照推 GitCode。

用法:
  uv run model-agent-rag publish init                          # 一次性初始化 artifacts/ 克隆
  uv run model-agent-rag publish [仓库名 ...]                  # 全流程:爬取 → 熔断 → 向量化 → 推送
  uv run model-agent-rag publish --skip-crawl [--dry-run]      # 跳过爬取,直接重算/发布
  uv run model-agent-rag publish --push-only                   # 仅补推上次本地已提交快照
"""

from __future__ import annotations

import fcntl
import os
import shutil
import subprocess
import sys
import time
import urllib.request
from contextlib import contextmanager
from datetime import datetime
from typing import TYPE_CHECKING
from zoneinfo import ZoneInfo

from loguru import logger

from src.corpus import APP_TZ, CACHE, CORPUS, DATA, EMBED_DIM, atomic_write_text
from src.ingest import CHUNK_SIZE, MIN_CHARS, export_corpus_points
from src.manifest import (
    SCHEMA_VERSION,
    ChunkConf,
    Manifest,
    append_history,
    load_manifest,
    save_manifest,
)

if TYPE_CHECKING:
    from collections.abc import Generator
    from pathlib import Path

os.environ.setdefault("GIT_LFS_SKIP_SMUDGE", "1")

DATA_REPO_PUSH = os.getenv(
    "DATA_REPO_PUSH", "git@gitcode.com:starmountain/ascend-rag-data.git"
)
ARTIFACTS = DATA.parent / "artifacts"
LOCK = CACHE / "publish.lock"
GIT_NAME, GIT_EMAIL = "guozr", "guozr1997@hotmail.com"

REPO_README = """\
# ascend-rag-data

rag(gitcode.com/starmountain/model-agent 的 rag 子栈)的向量知识库分发仓,
由构建机 `model-agent-rag publish` 定期产出快照,部署机由 `model-agent-rag sync`
按需拉取热更新(零停机、零黑窗)。

- `manifest.json`:普通 git 文件(单一真相源:snapshot_id、embed_model、全部 scope 元数据、
  parquet sha256 与每日点数历史)
- `points/<repo>/<lang>.parquet`:Git LFS(内容寻址向量点集,行按 ID 排序 + zstd,
  未变 scope 字节不变、零重传)
"""


def _git(*args: str) -> subprocess.CompletedProcess[str]:
    return subprocess.run(
        ["git", "-C", str(ARTIFACTS), *args],
        check=False,
        capture_output=True,
        text=True,
    )


def _g(*args: str, check: bool = True) -> str:
    r = _git(*args)
    if check and r.returncode:
        raise RuntimeError(f"git {args[:2]} 失败: {r.stderr.strip()}")
    return r.stdout


@contextmanager
def _locked() -> Generator[None, None, None]:
    LOCK.parent.mkdir(parents=True, exist_ok=True)
    with LOCK.open("w") as f:
        try:
            fcntl.flock(f, fcntl.LOCK_EX | fcntl.LOCK_NB)
        except BlockingIOError:
            raise SystemExit(f"已有 publish 在跑({LOCK})") from None
        yield


def _require_clone() -> None:
    if not (ARTIFACTS / ".git").is_dir():
        raise SystemExit(
            f"{ARTIFACTS} 不是数据仓 clone:请先运行 uv run model-agent-rag publish init"
        )


def _http_200(url: str, timeout: float = 5) -> bool:
    try:
        urllib.request.urlopen(url, timeout=timeout)
        return True
    except OSError:
        return False


def _repo_md_counts(root: Path) -> dict[str, int]:
    """统计 <source>/<repo> 维度的 .md 文件数(修复旧版只检查到 source 层的漏检问题)。"""
    counts: dict[str, int] = {}
    if not root.is_dir():
        return counts
    for src_dir in sorted(p for p in root.iterdir() if p.is_dir()):
        for repo_dir in sorted(p for p in src_dir.iterdir() if p.is_dir()):
            n = sum(1 for _ in repo_dir.rglob("*.md"))
            if n > 0:
                counts[f"{src_dir.name}/{repo_dir.name}"] = n
    return counts


def seed_staging(live_root: Path, staging_root: Path) -> None:
    """用硬链接把现有活语料快速播种到 staging(零额外磁盘、不污染活目录)。"""
    if staging_root.exists():
        shutil.rmtree(staging_root)
    if not live_root.is_dir():
        staging_root.mkdir(parents=True, exist_ok=True)
        return

    def _hardlink_or_copy(src: str, dst: str) -> str:
        try:
            os.link(src, dst)
        except OSError:
            shutil.copy2(src, dst)
        return dst

    shutil.copytree(live_root, staging_root, copy_function=_hardlink_or_copy)


def check_corpus_shrink(
    old_root: Path,
    new_root: Path,
    *,
    max_drop_pct: int = 2,
    min_abs_drop: int = 500,
) -> None:
    """缩库熔断:整仓 (source/repo) 消失或总 md 跌幅超阈值即中止。"""
    old_counts = _repo_md_counts(old_root)
    if not old_counts:
        return
    new_counts = _repo_md_counts(new_root)
    gone = sorted(set(old_counts) - set(new_counts))
    if gone:
        raise RuntimeError(f"缩库熔断:整仓目录消失: {' '.join(gone)}")
    old_total = sum(old_counts.values())
    new_total = sum(new_counts.values())
    dropped = old_total - new_total
    limit = max(min_abs_drop, old_total * max_drop_pct // 100)
    if dropped > limit:
        raise RuntimeError(
            f"缩库熔断:语料 md 文件 {old_total} -> {new_total}(减少 {dropped} > 阈值 {limit})"
        )


def check_points_shrink(
    prev_total: int, new_total: int, *, max_drop_pct: int = 10
) -> None:
    """点数熔断:总点数比上版跌超 max_drop_pct% 即中止发布。"""
    if prev_total > 0 and new_total < prev_total * (100 - max_drop_pct) / 100:
        raise RuntimeError(
            f"点数熔断:总点数 {prev_total} -> {new_total}(跌超 {max_drop_pct}%),中止发布"
        )


def has_scope_changes(prev: Manifest | None, curr: Manifest) -> bool:
    """判断两份 manifest 的有效数据内容(模型/维度/切分/全部 scope)是否有实质变化。"""
    if prev is None:
        return True
    return (
        prev.embed_model != curr.embed_model
        or prev.embed_dim != curr.embed_dim
        or prev.chunk_conf != curr.chunk_conf
        or prev.scopes != curr.scopes
    )


def _atomic_swap_dir(staging: Path, live: Path) -> None:
    backup = live.with_name(f"{live.name}.old.{os.getpid()}")
    if backup.exists():
        shutil.rmtree(backup)
    live.parent.mkdir(parents=True, exist_ok=True)
    had_live = live.exists()
    if had_live:
        os.rename(live, backup)
    try:
        os.rename(staging, live)
    except BaseException:
        if had_live and backup.exists() and not live.exists():
            os.rename(backup, live)
        raise
    if backup.exists():
        shutil.rmtree(backup, ignore_errors=True)


def _push(*, force: bool = True) -> bool:
    r = _git("push", *(["-f"] if force else []), "origin", "main:main")
    if r.returncode:
        logger.error(f"推送失败(本地快照已保留,稍后 --push-only 补推): {r.stderr.strip()}")
        return False
    logger.info((r.stderr or "已推送").strip().splitlines()[-1])
    return True


def cmd_init() -> None:
    if ARTIFACTS.exists() and any(ARTIFACTS.iterdir()):
        raise SystemExit(f"{ARTIFACTS} 已存在:clone 落位过就不再动")
    if subprocess.run(["git", "lfs", "version"], check=False, capture_output=True).returncode:
        raise SystemExit("缺 git-lfs:请先安装 git-lfs 后再执行 publish init")

    logger.info(f"clone {DATA_REPO_PUSH} -> {ARTIFACTS}")
    subprocess.run(["git", "clone", DATA_REPO_PUSH, str(ARTIFACTS)], check=True)
    if not _g("config", "user.email", check=False).strip():
        _g("config", "user.name", GIT_NAME)
        _g("config", "user.email", GIT_EMAIL)
    subprocess.run(["git", "-C", str(ARTIFACTS), "lfs", "install"], check=True)
    atomic_write_text(ARTIFACTS / "README.md", REPO_README)
    ga = ARTIFACTS / ".gitattributes"
    attrs = ga.read_text(encoding="utf-8") if ga.exists() else ""
    if "points/**" not in attrs:
        atomic_write_text(
            ga,
            attrs
            + ("" if not attrs or attrs.endswith("\n") else "\n")
            + "points/** filter=lfs diff=lfs merge=lfs -text\n",
        )
    logger.info(f"init 完成: {ARTIFACTS}")


def _crawl_with_staging(names: list[str]) -> None:
    staging = CACHE / "corpus-staging"
    logger.info("播种 staging 语料目录…")
    seed_staging(CORPUS, staging)
    try:
        scope = f"({'+'.join(names)})" if names else ""
        logger.info(f"全量爬取三源{scope} → staging…")
        subprocess.run(
            [sys.executable, "-m", "src.sources", *names],
            check=True,
            env={**os.environ, "CORPUS_DIR": str(staging)},
        )
        check_corpus_shrink(CORPUS, staging)
        _atomic_swap_dir(staging, CORPUS)
    except BaseException:
        shutil.rmtree(staging, ignore_errors=True)
        raise


def _handle_pending_push(*, push_only: bool) -> bool:
    """处理上次未推送的本地提交;返回 True 表示本次 publish 应提前结束。"""
    if _g("rev-list", "origin/main..main").strip():
        if not _push(force=True):
            raise SystemExit("快照补推失败:数据在本地,稍后重跑 --push-only")
        logger.info("上轮快照已补推")
        return push_only
    if push_only:
        logger.info("无待补推快照")
        return True
    return False


def _export_and_build_manifest(
    prev_manifest: Manifest | None,
    *,
    embed_base: str,
    embed_model: str,
) -> Manifest:
    """导出全部 scope 的确定性 parquet、执行点数熔断并组装新 Manifest。"""
    points_dir = ARTIFACTS / "points"
    points_dir.mkdir(parents=True, exist_ok=True)
    endpoints = [embed_base] if not os.getenv("EMBED_ENDPOINTS") else None
    scopes, _skipped = export_corpus_points(
        CORPUS,
        points_dir,
        repos=None,
        embed_endpoints=endpoints,
        embed_model=embed_model,
    )
    new_total = sum(s.point_count for s in scopes)
    if prev_manifest is not None:
        check_points_shrink(prev_manifest.total_points, new_total)

    snap_id = datetime.now(ZoneInfo(APP_TZ)).isoformat(timespec="seconds")
    manifest = Manifest(
        schema_version=SCHEMA_VERSION,
        snapshot_id=snap_id,
        embed_model=embed_model,
        embed_dim=EMBED_DIM,
        chunk_conf=ChunkConf(CHUNK_SIZE, MIN_CHARS),
        scopes=tuple(sorted(scopes, key=lambda s: s.key)),
        history=append_history(
            prev_manifest.history if prev_manifest else (), new_total
        ),
    )
    live_parquets = {s.parquet for s in manifest.scopes}
    for pq_file in points_dir.rglob("*.parquet"):
        rel = f"points/{pq_file.relative_to(points_dir).as_posix()}"
        if rel not in live_parquets:
            pq_file.unlink()
    return manifest


def _stage_and_push_snapshot(manifest: Manifest, *, dry_run: bool, t0: float) -> None:
    """写入数据仓清单、清理旧遗留文件,并按需压为单提交快照推送。"""
    _g(
        "rm",
        "-rfq",
        "--ignore-unmatch",
        "corpus",
        "corpus.tar.gz",
        "qdrant.tar.gz.part-*",
        "corpus_stats.json",
        "qdrant",
    )
    save_manifest(ARTIFACTS / "manifest.json", manifest)
    atomic_write_text(ARTIFACTS / "README.md", REPO_README)
    atomic_write_text(
        ARTIFACTS / ".gitattributes",
        "points/** filter=lfs diff=lfs merge=lfs -text\n",
    )
    _g("add", "-A")

    if dry_run:
        logger.info(
            f"--dry-run: {len(manifest.scopes)} scope, {manifest.total_points} 点(不提交不推送)",
        )
        _g("reset", "--hard", "origin/main")
        _g("clean", "-qfd")
        return

    new_commit = _g(
        "commit-tree",
        _g("write-tree").strip(),
        "-m",
        f"snapshot: {manifest.snapshot_id} ({manifest.total_points} pts)",
    ).strip()
    _g("update-ref", "refs/heads/main", new_commit)
    if not _push(force=True):
        raise SystemExit("快照推送失败:数据在本地,稍后重跑 --push-only 补推")
    pfs = sorted((ARTIFACTS / "points").rglob("*.parquet"))
    logger.info(
        f"发布完成: snapshot={manifest.snapshot_id}, {manifest.total_points} 点, "
        f"{len(pfs)} parquet ({sum(p.stat().st_size for p in pfs) / 2**30:.2f} GiB), "
        f"用时 {time.time() - t0:.0f}s",
    )


def cmd_publish(
    names: list[str], *, skip_crawl: bool, dry_run: bool, push_only: bool
) -> None:
    _require_clone()
    with _locked():
        t0 = time.time()
        _g("fetch", "origin")
        if _handle_pending_push(push_only=push_only):
            return

        _g("reset", "--hard", "origin/main")
        _g("clean", "-qfd")

        embed_base = os.getenv("EMBED_BASE_URL", "http://127.0.0.1:8001/v1")
        embed_model = os.getenv("EMBED_MODEL", "Qwen/Qwen3-Embedding-0.6B")
        health_url = f"{embed_base.rstrip('/').removesuffix('/v1')}/health"
        if not _http_200(health_url):
            raise SystemExit(f"embedding 不可达({health_url}):请先启动 NPU embedding 服务")

        if not skip_crawl:
            _crawl_with_staging(names)

        prev_manifest = load_manifest(ARTIFACTS / "manifest.json")
        manifest = _export_and_build_manifest(
            prev_manifest, embed_base=embed_base, embed_model=embed_model
        )
        if not has_scope_changes(prev_manifest, manifest):
            _g("reset", "--hard", "origin/main")
            _g("clean", "-qfd")
            logger.info(f"所有 scope 字节无变化,零推送(用时 {time.time() - t0:.0f}s)")
            return

        _stage_and_push_snapshot(manifest, dry_run=dry_run, t0=t0)


def main(args: list[str] | None = None) -> None:
    argv = sys.argv[1:] if args is None else args
    if argv[:1] == ["init"]:
        cmd_init()
        return
    skip_crawl = "--skip-crawl" in argv
    dry_run = "--dry-run" in argv
    push_only = "--push-only" in argv
    names = [a for a in argv if not a.startswith("-")]
    try:
        cmd_publish(
            names, skip_crawl=skip_crawl, dry_run=dry_run, push_only=push_only
        )
    except (RuntimeError, subprocess.CalledProcessError) as e:
        raise SystemExit(f"发布失败: {e}") from e


if __name__ == "__main__":
    main()