"""列出所有已入库的因子。

以 Python 列表格式输出所有已注册因子的名称，方便复制使用。
保持 factors.jsonl 中的原始顺序（按 factor_id）。

使用方法:
    uv run python -m src.scripts.list_factors
"""

import json
import re
from pathlib import Path

from src.config.settings import get_settings


def extract_factor_id_number(factor_id: str) -> int:
    """从 factor_id 中提取数字部分用于排序。

    Args:
        factor_id: 如 "F_001"

    Returns:
        数字部分，如 1
    """
    match = re.match(r"F_(\d+)", factor_id)
    if match:
        return int(match.group(1))
    return 0


def list_factors():
    """读取 factors.jsonl 并按 factor_id 顺序打印因子名称列表。"""
    settings = get_settings()
    factors_path = settings.data_path_resolved / "factors.jsonl"

    if not factors_path.exists():
        print(f"[错误] 因子文件不存在: {factors_path}")
        return

    # 读取所有因子并按 factor_id 排序
    factors = []
    try:
        with open(factors_path, "r", encoding="utf-8") as f:
            for line in f:
                line = line.strip()
                if not line:
                    continue
                try:
                    data = json.loads(line)
                    factor_id = data.get("factor_id", "")
                    name = data.get("name")
                    if name and factor_id:
                        factors.append((factor_id, name))
                except json.JSONDecodeError:
                    continue
    except Exception as e:
        print(f"[错误] 读取因子文件失败: {e}")
        return

    if not factors:
        print("[信息] 没有找到任何因子")
        return

    # 按 factor_id 数字排序（保持入库顺序）
    factors.sort(key=lambda x: extract_factor_id_number(x[0]))

    # 以 Python 列表格式输出
    print("[")
    for i, (factor_id, name) in enumerate(factors):
        if i == len(factors) - 1:
            print(f'    "{name}"')
        else:
            print(f'    "{name}",')
    print("]")

    print(f"\n[统计] 共计 {len(factors)} 个因子")


if __name__ == "__main__":
    list_factors()
