"""Model search tool: fuzzy-search ACL_PyTorch built-in models by name and extract supported hardware types."""

import re
import argparse
import os
from pathlib import Path

BASE_DIR = Path(__file__).resolve().parent
GITCODE_URL_PREFIX = "https://gitcode.com/Ascend/ModelZoo-PyTorch/tree/master/ACL_PyTorch/"
BUILTIN_PREFIX = "built-in/"
MODELZOO_GPL_FLAG = "modelzoo-GPL"


def parse_modelist(modelist_path):
    """Parse ModeList.md and return model list [(name, link_path, intro, display_name), ...].

    display_name is the link text from the ModeList table; for modelzoo-GPL YOLO
    models it is used as the output folder name.
    """
    models = []
    with open(modelist_path, "r", encoding="utf-8") as f:
        content = f.read()
    row_pattern = re.compile(
        r"^\|\s*([^|]+?)\s*\|\s*\[([^\]]*)\]\(([^)]+)\)\s*\|\s*([^|]*)\s*\|\s*$"
    )
    for line in content.splitlines():
        match = row_pattern.match(line)
        if not match:
            continue
        name, display_name, path, intro = match.groups()
        if path.startswith("#"):
            continue
        if not (path.startswith(BUILTIN_PREFIX) or MODELZOO_GPL_FLAG in path):
            continue
        models.append(
            (
                name.replace("\\_", "_"),
                path,
                intro.replace("\\_", "_").strip(),
                display_name.replace("\\_", "_"),
            )
        )
    return models


def extract_hardware(readme_path):
    """Extract supported hardware types from the README performance table.

    Locates the header row containing the "芯片" keyword, then extracts chip
    models column by column, deduplicating while preserving order. Compatible
    with both "芯片型号"/"芯片" header naming and any column position (e.g.
    CosyVoice2 has the chip column at index 2).
    """
    if not readme_path or not os.path.exists(readme_path):
        return "未知"
    with open(readme_path, "r", encoding="utf-8") as f:
        lines = f.read().splitlines()
    hardware = []
    chip_col_idx = -1
    in_table = False
    for line in lines:
        stripped = line.strip()
        if not in_table:
            if stripped.startswith("|") and "芯片" in stripped:
                cells = [c.strip() for c in stripped.split("|")]
                for idx, cell in enumerate(cells):
                    if "芯片" in cell:
                        chip_col_idx = idx
                        break
                if chip_col_idx >= 0:
                    in_table = True
            continue
        if not stripped.startswith("|"):
            break
        cells = [c.strip() for c in stripped.split("|")]
        if chip_col_idx >= len(cells):
            continue
        val = cells[chip_col_idx]
        if re.fullmatch(r"[\s:\-]+", val):
            continue
        if val:
            hardware.append(val)
    if not hardware:
        return "未知"
    seen = []
    for h in hardware:
        if h not in seen:
            seen.append(h)
    return ", ".join(seen)


def get_hardware_type(path):
    """Return supported hardware type based on the link path."""
    if MODELZOO_GPL_FLAG in path:
        return "以readme为准"
    model_dir = str(BASE_DIR / path)
    readme_path = None
    if os.path.isdir(model_dir):
        for name in os.listdir(model_dir):
            if name.lower() == "readme.md":
                readme_path = os.path.join(model_dir, name)
                break
    return extract_hardware(readme_path)


def search_models(models, keyword):
    """Case-insensitive fuzzy match by keyword, sorted by relevance descending."""
    kw = keyword.lower()
    matched = [m for m in models if kw in m[0].lower()]
    if "yolo" in kw:
        matched = [m for m in matched if MODELZOO_GPL_FLAG in m[1]]

    def _relevance(name):
        name_lower = name.lower()
        if name_lower == kw:
            return 1000
        if name_lower.startswith(kw):
            return 500 + len(name) - len(kw)
        return 100 - name_lower.find(kw)

    matched.sort(key=lambda m: (-_relevance(m[0]), m[0].lower()))
    return matched


def format_output(matched):
    """Format matched results; multiple models separated by divider lines."""
    if not matched:
        return "未找到匹配的模型"
    sep = "-" * 50
    blocks = []
    for name, path, intro, display_name in matched:
        folder = display_name if MODELZOO_GPL_FLAG in path else path
        url = path if path.startswith("http") else GITCODE_URL_PREFIX + path
        blocks.append(
            f"模型名称: {name}\n"
            f"文件夹名称: {folder}\n"
            f"网址链接: {url}\n"
            f"简介: {intro}\n"
            f"支持硬件类型: {get_hardware_type(path)}"
        )
    return ("\n" + sep + "\n").join(blocks)


if __name__ == "__main__":
    parser = argparse.ArgumentParser(
        description="Fuzzy-search ACL_PyTorch built-in models by name and show supported hardware types"
    )
    parser.add_argument(
        "--modelname", type=str, required=True, help="Model name keyword (case-insensitive)"
    )
    args = parser.parse_args()

    models = parse_modelist(BASE_DIR / "ModeList.md")
    print(format_output(search_models(models, args.modelname)))