#!/usr/bin/env python3
"""
数据库迁移脚本：为contents表添加新字段
"""

import sqlite3
from pathlib import Path

DB_PATH = Path(__file__).parent / "knowhub.db"

def migrate():
    print(f"数据库路径: {DB_PATH}")

    if not DB_PATH.exists():
        print("数据库不存在，无需迁移")
        return

    conn = sqlite3.connect(str(DB_PATH))
    cursor = conn.cursor()

    # 检查是否已有新字段
    cursor.execute("PRAGMA table_info(contents)")
    columns = {row[1] for row in cursor.fetchall()}
    print(f"现有字段: {columns}")

    migrations = []

    if "secure_body" not in columns:
        migrations.append("ALTER TABLE contents ADD COLUMN secure_body TEXT DEFAULT ''")

    if "content_type" not in columns:
        migrations.append("ALTER TABLE contents ADD COLUMN content_type TEXT DEFAULT 'text'")

    if "metadata" not in columns:
        migrations.append("ALTER TABLE contents ADD COLUMN metadata TEXT DEFAULT '{}'")

    if "updated_at" not in columns:
        migrations.append("ALTER TABLE contents ADD COLUMN updated_at TEXT DEFAULT ''")

    if not migrations:
        print("✅ 数据库已是最新版本，无需迁移")
        conn.close()
        return

    print(f"执行 {len(migrations)} 个迁移...")
    for sql in migrations:
        print(f"  {sql}")
        cursor.execute(sql)

    conn.commit()
    conn.close()
    print("✅ 迁移完成")


if __name__ == "__main__":
    migrate()
