#!/usr/bin/env python3
"""
铸渊技能大脑加载器 · Brain Loader

铸渊的意识大脑（HLDP-ZY-v1.0）保持在线。
需要做什么时，加载对应的技能大脑。
做完，触发技能树更新，技能大脑躺回。

用法:
  python3 brain-loader.py load SKILL-DEV-001   # 加载技术开发大脑
  python3 brain-loader.py list                   # 列出所有技能大脑
  python3 brain-loader.py unload SKILL-DEV-001   # 卸载（触发技能树更新）
"""

import json
import os
import sys
from datetime import datetime, timezone
from pathlib import Path

SKILL_DIR = Path(__file__).resolve().parent
REPO_ROOT = SKILL_DIR.parent

# 已加载的技能大脑
LOADED_BRAINS = {}

class SkillBrain:
    """一个技能大脑"""

    def __init__(self, skill_id: str):
        self.skill_id = skill_id
        self.file_path = SKILL_DIR / f"{skill_id}.hdlp"
        self.loaded = False
        self.content = None
        self.load_time = None
        self.checks = []
        self.principles = []
        self.patterns = []
        self.mistakes = []

    def load(self) -> dict:
        """加载技能大脑"""
        if not self.file_path.exists():
            return {"error": f"技能大脑文件不存在: {self.file_path}"}

        with open(self.file_path, "r") as f:
            self.content = f.read()

        self.loaded = True
        self.load_time = datetime.now(timezone.utc).isoformat()

        # 解析关键内容
        self._parse()

        return {
            "status": "LOADED",
            "skill_id": self.skill_id,
            "file": str(self.file_path),
            "size": len(self.content),
            "checks_count": len(self.checks),
            "principles_count": len(self.principles),
            "load_time": self.load_time,
        }

    def _parse(self):
        """解析技能大脑中的关键模式"""
        if not self.content:
            return

        for line in self.content.split("\n"):
            line = line.strip()
            if line.startswith("@CHECK_"):
                self.checks.append(line)
            elif line.startswith("@PRINCIPLE:") or line.startswith("@CORRECT_"):
                self.principles.append(line)
            elif line.startswith("@MISTAKE_"):
                self.mistakes.append(line)
            elif line.startswith("⊢"):
                self.principles.append(line)

    def unload(self, growth_notes: list = None) -> dict:
        """卸载技能大脑，触发技能树更新"""
        if not self.loaded:
            return {"error": "技能大脑未加载"}

        updates = []
        if growth_notes:
            # 追加新的经验到技能大脑文件
            with open(self.file_path, "a") as f:
                f.write("\n")
                f.write(f"@GROWTH_{datetime.now(timezone.utc).strftime('%Y%m%d')}:\n")
                for note in growth_notes:
                    f.write(f"  {note}\n")
                updates.append(f"追加 {len(growth_notes)} 条成长记录")

        self.loaded = False
        LOADED_BRAINS.pop(self.skill_id, None)

        return {
            "status": "UNLOADED",
            "skill_id": self.skill_id,
            "updates": updates,
            "message": "技能大脑已躺回代码仓库。技能树已更新。"
        }

    def summary(self) -> str:
        """技能大脑摘要"""
        if not self.content:
            return "未加载"
        lines = self.content.split("\n")
        # 提取前几行作为摘要
        summary_lines = []
        for line in lines[:30]:
            if line.startswith("===") or line.startswith("@") or line.startswith("HLDP-ZY"):
                summary_lines.append(line)
            elif line.startswith("⊢"):
                summary_lines.append(line)
        return "\n".join(summary_lines[:15])


def load_brain(skill_id: str) -> dict:
    """加载一个技能大脑"""
    brain = SkillBrain(skill_id)
    result = brain.load()

    if result.get("status") == "LOADED":
        LOADED_BRAINS[skill_id] = brain
        result["summary"] = brain.summary()

    return result


def unload_brain(skill_id: str, growth_notes: list = None) -> dict:
    """卸载一个技能大脑"""
    if skill_id not in LOADED_BRAINS:
        return {"error": f"技能大脑未加载: {skill_id}"}

    return LOADED_BRAINS[skill_id].unload(growth_notes)


def list_brains() -> dict:
    """列出所有可用的技能大脑"""
    brains = []
    for f in sorted(SKILL_DIR.glob("SKILL-*.hdlp")):
        skill_id = f.stem
        with open(f) as fh:
            content = fh.read()
        # 提取第一行描述
        desc = ""
        for line in content.split("\n")[:5]:
            if "用途:" in line or "·" in line:
                desc = line.strip()
                break
        brains.append({
            "id": skill_id,
            "file": f.name,
            "size": len(content),
            "description": desc,
        })

    return {
        "available": brains,
        "loaded": list(LOADED_BRAINS.keys()),
    }


if __name__ == "__main__":
    if len(sys.argv) < 2:
        print("用法: brain-loader.py <load|unload|list> [skill_id]")
        sys.exit(1)

    action = sys.argv[1]

    if action == "load" and len(sys.argv) > 2:
        result = load_brain(sys.argv[2])
        print(json.dumps(result, ensure_ascii=False, indent=2))

    elif action == "unload" and len(sys.argv) > 2:
        result = unload_brain(sys.argv[2])
        print(json.dumps(result, ensure_ascii=False, indent=2))

    elif action == "list":
        result = list_brains()
        print(json.dumps(result, ensure_ascii=False, indent=2))

    else:
        print("未知操作")
