#!/usr/bin/env python3
"""reading-notes: 读书笔记"""
import json, sys
from datetime import datetime
from pathlib import Path

SKILL_DIR = Path.home() / ".openclaw/skills/reading-notes"
DATA_FILE = SKILL_DIR / "notes.jsonl"

def init_data():
    SKILL_DIR.mkdir(parents=True, exist_ok=True)

def add_note(book, content, page=None, chapter=None):
    init_data()
    note = {
        "id": f"note-{datetime.now().strftime('%Y%m%d%H%M%S')}",
        "book": book,
        "content": content,
        "page": page,
        "chapter": chapter,
        "created": datetime.now().strftime('%Y-%m-%d')
    }
    with open(DATA_FILE, 'a', encoding='utf-8') as f:
        f.write(json.dumps(note, ensure_ascii=False) + '\n')
    print(f"✅ 笔记已保存（《{book}》）")

def list_notes(book=None):
    init_data()
    notes = []
    if DATA_FILE.exists():
        with open(DATA_FILE, 'r', encoding='utf-8') as f:
            for line in f:
                if line.strip():
                    try:
                        n = json.loads(line)
                        if book and n.get('book') != book:
                            continue
                        notes.append(n)
                    except:
                        pass
    if not notes:
        print("📭 暂无读书笔记")
        return
    current_book = None
    for n in notes[-30:]:
        if n['book'] != current_book:
            current_book = n['book']
            print(f"\n📚 《{current_book}》")
        loc = []
        if n.get('chapter'):
            loc.append(f"第{n['chapter']}章")
        if n.get('page'):
            loc.append(f"P{n['page']}")
        loc_str = ' '.join(loc)
        print(f"  • {n['content'][:80]}{'...' if len(n['content'])>80 else ''} {loc_str}")

def main():
    if len(sys.argv) < 2:
        print("用法: reading_notes.py 添加 书名 '笔记内容' [页码] [章节]")
        print("      reading_notes.py 列表 [书名]")
        return
    cmd = sys.argv[1]
    if cmd in ['添加', 'add']:
        if len(sys.argv) < 4:
            print("❌ 需要书名和笔记内容")
            return
        add_note(sys.argv[2], sys.argv[3], sys.argv[4] if len(sys.argv)>4 else None, sys.argv[5] if len(sys.argv)>5 else None)
    elif cmd in ['列表', 'list']:
        list_notes(sys.argv[2] if len(sys.argv)>2 else None)

if __name__ == '__main__':
    main()
