import csv
import yaml
import json
from collections import defaultdict
from pathlib import Path


CSV_PATH = "instruction/镜频指令抽取.csv"
YAML_OUT = "instruction/instruction_library.yaml"
JSON_OUT = "instruction/instruction_library.json"


def load_csv(path: str):
    rows = []
    with open(path, "r", encoding="utf-8", newline="") as f:
        reader = csv.DictReader(f)
        for r in reader:
            rows.append(r)
    return rows


def build_instruction_library(rows):
    devices = defaultdict(lambda: {"index": None, "commands": []})
    global_commands = []

    for row in rows:
        device = row["设备名称"].strip()
        index = row["设备索引"].strip()
        name = row["指令名称"].strip()
        cmd_id = row["指令编号"].strip()
        ret = row["返回值"].strip()
        desc = row["指令描述"].strip()
        role = row["指令角色"].strip()

        # 指令类型转换
        type_map = {
            "构造函数": "constructor",
            "普通指令": "normal",
            "循环开始": "loop_begin",
            "循环结束": "loop_end",
        }
        cmd_type = type_map.get(role, "normal")

        cmd_obj = {
            "name": name,
            "id": cmd_id,
            "return": ret if ret else "",
            "description": desc,
            "type": cmd_type
        }

        if device == "" or device is None:
            # 无设备 → 全局指令
            global_commands.append(cmd_obj)
        else:
            # 有设备 → 写入设备指令
            if devices[device]["index"] is None:
                devices[device]["index"] = int(index)

            devices[device]["commands"].append(cmd_obj)

    return {
        "devices": devices,
        "global_commands": global_commands
    }


def save_yaml(data, path):
    with open(path, "w", encoding="utf-8") as f:
        yaml.dump(data, f, allow_unicode=True, sort_keys=False)


def save_json(data, path):
    with open(path, "w", encoding="utf-8") as f:
        json.dump(data, f, ensure_ascii=False, indent=2)


if __name__ == "__main__":
    print("📥 Loading CSV...")
    rows = load_csv(CSV_PATH)

    print("🔧 Building instruction library...")
    lib = build_instruction_library(rows)

    print("💾 Saving YAML...")
    save_yaml(lib, YAML_OUT)

    print("💾 Saving JSON...")
    save_json(lib, JSON_OUT)

    print("\n🎉 Done! Instruction library generated:")
    print(f" - YAML: {YAML_OUT}")
    print(f" - JSON: {JSON_OUT}")
