#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
resolve_source_input.py —— PPT 工作流素材入口解析。

用途：
  - inputs.source 明确给了路径：验证并返回该路径。
  - inputs.source 为空，但用户自然语言里说了「下载目录里的某 Word 文件」：
    在 Downloads / Desktop / cwd 内做受限搜索，找到唯一候选。
  - 明确提到素材文件却找不到或多候选：写报告并退出非 0，避免下游伪装成纯 topic。

只做受限目录搜索，不全盘扫描。
"""

import argparse
import json
import os
import re
import sys
import unicodedata
from dataclasses import dataclass


SUPPORTED_EXTS = (
    ".doc", ".docx", ".ppt", ".pptx", ".pdf", ".xlsx", ".xls", ".csv", ".tsv",
    ".png", ".jpg", ".jpeg", ".gif", ".webp", ".bmp", ".tif", ".tiff",
)
WORD_EXTS = (".doc", ".docx")
FILE_HINT_PATTERNS = (
    r"[/\\]",
    r"\.(doc|docx|ppt|pptx|pdf|xlsx|xls|csv|tsv|png|jpe?g|webp|gif)\b",
    r"下载目录|Downloads|download",
    r"桌面|Desktop|desktop",
    r"Word\s*文件|word\s*文件|老\s*Word|老\s*word",
    r"PPT\s*文件|ppt\s*文件|PowerPoint",
    r"PDF\s*文件|pdf\s*文件",
    r"源文件|素材文件|材料文件|文档文件",
)
STOP_WORDS = {
    "用", "我", "电脑", "下载", "目录", "里面", "里的", "word", "Word", "WORD",
    "文件", "作为", "基础", "生成", "一套", "专业", "中文", "PPT", "ppt",
    "整体感", "不要", "卡片", "堆叠", "的", "和", "把",
}


@dataclass
class Candidate:
    path: str
    score: int
    reason: str


def _norm(text: str) -> str:
    text = unicodedata.normalize("NFKC", text or "")
    return re.sub(r"\s+", "", text).lower()


def _tokens(text: str) -> list[str]:
    raw = unicodedata.normalize("NFKC", text or "")
    parts = re.split(r"[\s/\\,，。；;:：\"'“”‘’()（）【】\[\]<>《》|]+", raw)
    out: list[str] = []
    for p in parts:
        p = p.strip()
        if not p or p in STOP_WORDS:
            continue
        if len(p) <= 1 and not re.search(r"[\u4e00-\u9fff]", p):
            continue
        out.append(p)
    return out


def mentions_source(topic: str, source: str) -> bool:
    if source.strip():
        return True
    return any(re.search(pat, topic or "", re.I) for pat in FILE_HINT_PATTERNS)


def search_roots(cwd: str, home: str, topic: str) -> list[str]:
    roots = [cwd]
    if "下载目录" in topic or "Downloads" in topic or "download" in topic.lower():
        roots.insert(0, os.path.join(home, "Downloads"))
    else:
        roots.append(os.path.join(home, "Downloads"))
    if "桌面" in topic or "Desktop" in topic or "desktop" in topic.lower():
        roots.insert(0, os.path.join(home, "Desktop"))
    else:
        roots.append(os.path.join(home, "Desktop"))
    seen = set()
    out = []
    for r in roots:
        r = os.path.abspath(os.path.expanduser(r))
        if r not in seen and os.path.isdir(r):
            seen.add(r)
            out.append(r)
    return out


def list_files(root: str, max_depth: int = 2) -> list[str]:
    root = os.path.abspath(root)
    files: list[str] = []
    for cur, dirs, names in os.walk(root):
        depth = os.path.relpath(cur, root).count(os.sep)
        if depth >= max_depth:
            dirs[:] = []
        dirs[:] = [
            d for d in dirs
            if not d.startswith(".")
            and d not in {
                "node_modules", ".git", "vendor", "build", "out", "dist",
                "coverage", ".cache", "tmp", "temp",
            }
        ]
        for name in names:
            if name.startswith("~$") or name.startswith("."):
                continue
            if name.lower().endswith(SUPPORTED_EXTS):
                files.append(os.path.join(cur, name))
    return sorted(files)


def score_candidate(path: str, topic: str, source: str) -> Candidate | None:
    base = os.path.basename(path)
    ext = os.path.splitext(base)[1].lower()
    norm_base = _norm(os.path.splitext(base)[0])
    norm_topic = _norm(topic)
    score = 0
    reasons = []

    if source.strip():
        return Candidate(path, 10_000, "显式 source 路径")

    toks = _tokens(topic)
    for tok in toks:
        nt = _norm(tok)
        if not nt or nt in STOP_WORDS:
            continue
        if nt in norm_base:
            add = max(2, min(20, len(nt)))
            score += add
            reasons.append(tok)

    if ext in WORD_EXTS and re.search(r"word|doc|文档|文件", topic, re.I):
        score += 20
        reasons.append("Word 类型匹配")
    elif ext in (".ppt", ".pptx") and re.search(r"ppt|幻灯|课件", topic, re.I):
        score += 14
        reasons.append("PPT 类型匹配")
    elif ext in (".pdf",) and "pdf" in norm_topic:
        score += 12
        reasons.append("PDF 类型匹配")

    # 长中文片段包含是强证据。
    chinese_chunks = re.findall(r"[\u4e00-\u9fffA-Za-z0-9_]{4,}", topic)
    for ch in chinese_chunks:
        nch = _norm(ch)
        if len(nch) >= 6 and nch in norm_base:
            score += 30
            reasons.append(ch)

    if score <= 0:
        return None
    return Candidate(path, score, "、".join(reasons[:5]) or "文件名相似")


def resolve_source(source: str, topic: str, cwd: str, home: str) -> dict:
    source = (source or "").strip()
    topic = topic or ""
    explicit = bool(source)
    wants_source = mentions_source(topic, source)

    if explicit:
        path = os.path.abspath(os.path.expanduser(source))
        ok = os.path.exists(path)
        return {
            "ok": ok,
            "explicit": True,
            "requires_source": True,
            "resolved_path": path if ok else None,
            "candidates": [path] if ok else [],
            "message": "显式 source 路径有效" if ok else f"显式 source 路径不存在：{path}",
        }

    candidates: list[Candidate] = []
    seen_paths = set()
    explicit_dir_hint = any(x in topic for x in ("下载目录", "Downloads", "桌面", "Desktop"))
    if wants_source:
        for root in search_roots(cwd, home, topic):
            before = len(candidates)
            for f in list_files(root):
                real = os.path.realpath(f)
                if real in seen_paths:
                    continue
                seen_paths.add(real)
                cand = score_candidate(f, topic, source)
                if cand:
                    candidates.append(cand)
            # 用户明确说了下载目录/桌面时，命中该优先目录即可停止，
            # 避免继续扫大型仓库 cwd 导致入口阶段卡顿。
            if explicit_dir_hint and len(candidates) > before:
                break
    candidates.sort(key=lambda c: (-c.score, len(c.path), c.path))

    if not wants_source:
        return {
            "ok": True,
            "explicit": False,
            "requires_source": False,
            "resolved_path": None,
            "candidates": [],
            "message": "未检测到明确素材文件指令，允许扫描 cwd 或纯 topic 路径",
        }

    if not candidates:
        return {
            "ok": False,
            "explicit": False,
            "requires_source": True,
            "resolved_path": None,
            "candidates": [],
            "message": "用户提到素材文件，但在 Downloads/Desktop/cwd 未找到匹配候选",
        }

    top = candidates[0]
    tied = [c for c in candidates if c.score == top.score]
    if len(tied) > 1:
        return {
            "ok": False,
            "explicit": False,
            "requires_source": True,
            "resolved_path": None,
            "candidates": [{"path": c.path, "score": c.score, "reason": c.reason} for c in tied[:10]],
            "message": "用户提到素材文件，但存在多个同分候选，请显式传 --input source",
        }

    return {
        "ok": True,
        "explicit": False,
        "requires_source": True,
        "resolved_path": top.path,
        "candidates": [{"path": c.path, "score": c.score, "reason": c.reason} for c in candidates[:10]],
        "message": f"按自然语言解析到素材：{top.path}",
    }


def main() -> int:
    parser = argparse.ArgumentParser(description="解析 PPT 工作流输入里的素材路径")
    parser.add_argument("--source", default="", help="用户显式传入的素材路径")
    parser.add_argument("--topic", default="", help="用户原始自然语言指令")
    parser.add_argument("--cwd", default=".", help="工作流 cwd")
    parser.add_argument("--out", default="./build/source_resolution.json", help="解析报告输出路径")
    parser.add_argument("--home", default=os.path.expanduser("~"), help="测试用 home 覆盖")
    args = parser.parse_args()

    result = resolve_source(args.source, args.topic, args.cwd, args.home)
    os.makedirs(os.path.dirname(os.path.abspath(args.out)), exist_ok=True)
    with open(args.out, "w", encoding="utf-8") as f:
        json.dump(result, f, ensure_ascii=False, indent=2)
    print(result["message"])
    if result.get("ok"):
        if result.get("resolved_path"):
            print(f"RESOLVED_SOURCE={result['resolved_path']}")
        return 0
    print("SOURCE_RESOLUTION_FAILED", file=sys.stderr)
    for c in result.get("candidates", []):
        print(f"- {c}", file=sys.stderr)
    return 2


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