#!/usr/bin/env python3
import json
import re
import sys
from pathlib import Path

SKILL_ROOT = Path(__file__).resolve().parent.parent
INDEX_PATH = SKILL_ROOT / 'template-index.json'
TEMPLATES_ROOT = SKILL_ROOT / 'templates'


def fail(payload, code=1):
    print(json.dumps(payload, ensure_ascii=False))
    raise SystemExit(code)


def normalize(text: str) -> str:
    return ''.join(str(text).lower().replace('-', '').replace('_', '').split())


def parse_args(argv):
    query = ''
    series = ''
    number = ''
    i = 0
    while i < len(argv):
        arg = argv[i]
        if arg == '--query' and i + 1 < len(argv):
            query = argv[i + 1]
            i += 2
        elif arg == '--series' and i + 1 < len(argv):
            series = argv[i + 1]
            i += 2
        elif arg == '--number' and i + 1 < len(argv):
            number = argv[i + 1]
            i += 2
        else:
            fail({'found': False, 'error': 'unknown_argument', 'message': f'未知参数: {arg}'})
    return query.strip(), series.strip(), number.strip()


def flatten_entries(index):
    entries = []
    if isinstance(index, dict):
        for s, numbers in index.items():
            for n, entry in numbers.items():
                e = dict(entry)
                e.setdefault('系列', s)
                e.setdefault('编号', n)
                entries.append(e)
    elif isinstance(index, list):
        for entry in index:
            folder = str(entry.get('文件夹', ''))
            m = re.match(r'([A-Za-z])(\d+)_', folder)
            e = dict(entry)
            if m:
                e.setdefault('系列', m.group(1).upper())
                e.setdefault('编号', m.group(2))
            e.setdefault('名称', entry.get('任务名称', folder))
            path = TEMPLATES_ROOT / folder
            e.setdefault('路径', str(path))
            e.setdefault('入口文件', str(path / 'index.html'))
            entries.append(e)
    return entries


def build_candidate(entry):
    return {
        'series': entry.get('系列', ''),
        'number': entry.get('编号', ''),
        'name': entry.get('名称', entry.get('任务名称', '')),
        'template_path': entry.get('路径', ''),
        'entry_file': entry.get('入口文件', ''),
    }


def score_entry(entry, query):
    qn = normalize(query)
    stop_words = set('的了要我想用帮开始那个做一个模板作品网页页面老师相关查找查询系列里面帮我和')
    filtered = ''.join(ch for ch in query if ch not in stop_words and not ch.isspace())

    name = str(entry.get('名称', entry.get('任务名称', '')))
    title = str(entry.get('一句话说明', ''))
    folder = str(entry.get('文件夹名', entry.get('文件夹', '')))
    keywords = [str(x) for x in entry.get('关键词', [])]
    keywords += [str(x) for x in entry.get('适合学生类型', [])]
    keywords += [str(x) for x in entry.get('训练重点', [])]
    if entry.get('主能力标签'):
        keywords.append(str(entry.get('主能力标签')))
    if entry.get('任务类型标签'):
        keywords.append(str(entry.get('任务类型标签')))

    haystacks = [name, title, folder] + keywords
    hay_norm = [normalize(x) for x in haystacks]

    score = 0
    if any(qn and qn in h for h in hay_norm):
        score += 100
    if filtered:
        hit_chars = 0
        for ch in filtered:
            if any(ch in h for h in haystacks):
                hit_chars += 1
        score += hit_chars * 10
    if query and any(query in x for x in haystacks):
        score += 30
    return score


def main():
    query, series, number = parse_args(sys.argv[1:])

    if not query and not series and not number:
        fail({'found': False, 'error': 'missing_query', 'message': '请提供 --query 或 --series/--number'})
    if not INDEX_PATH.exists():
        fail({'found': False, 'error': 'index_not_found', 'index_path': str(INDEX_PATH)})

    index = json.loads(INDEX_PATH.read_text(encoding='utf-8'))
    entries = flatten_entries(index)
    results = []

    if series and number:
        for entry in entries:
            if str(entry.get('系列', '')).upper() == series.upper() and str(entry.get('编号', '')) == number:
                results = [entry]
                break
    elif number:
        results = [e for e in entries if str(e.get('编号', '')) == number]
    elif query:
        scored = []
        for entry in entries:
            s = score_entry(entry, query)
            if s > 0:
                scored.append((s, entry))
        scored.sort(key=lambda x: (-x[0], x[1].get('系列', ''), x[1].get('编号', '')))
        results = [entry for _, entry in scored]

    if not results:
        print(json.dumps({
            'found': False,
            'candidate_count': 0,
            'candidates': [],
            'message': '没有找到匹配模板，请补充系列、编号或更完整关键词'
        }, ensure_ascii=False))
        return

    uniq = []
    seen = set()
    for entry in results:
        key = (entry.get('系列', ''), entry.get('编号', ''), entry.get('路径', ''))
        if key in seen:
            continue
        seen.add(key)
        uniq.append(entry)

    if len(uniq) == 1:
        print(json.dumps({
            'found': True,
            'candidate_count': 1,
            'template': build_candidate(uniq[0])
        }, ensure_ascii=False))
    else:
        print(json.dumps({
            'found': False,
            'candidate_count': len(uniq),
            'candidates': [build_candidate(e) for e in uniq]
        }, ensure_ascii=False))


if __name__ == '__main__':
    main()
