#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
工作手机 SDK - 数据库初始化脚本
用途：创建 MongoDB 集合与索引
执行：cd sdk/app && python3 scripts/init_db.py
前置：MongoDB 已启动；若开启认证，需在 .env 中配置 MONGO_URI（含用户名密码）。
"""

import os
import sys

# 添加项目根目录
sys.path.insert(0, os.path.dirname(os.path.dirname(os.path.abspath(__file__))))

from pymongo import MongoClient
from pymongo.errors import CollectionInvalid
from config import settings


def init_database():
    """初始化 workphone_sdk 数据库"""
    client = MongoClient(settings.MONGO_URI)
    db = client[settings.MONGO_DB]

    print(f"=== 初始化数据库: {settings.MONGO_DB} ===")

    # devices
    try:
        db.create_collection("devices")
    except CollectionInvalid:
        pass
    db.devices.create_index("device_id", unique=True)
    db.devices.create_index("status")
    db.devices.create_index("last_heartbeat")
    print("✅ devices 索引已创建")

    # commands
    try:
        db.create_collection("commands")
    except CollectionInvalid:
        pass
    db.commands.create_index("device_id")
    db.commands.create_index("created_at")
    print("✅ commands 索引已创建")

    # execution_logs（可选，与 device_manager 保持一致）
    try:
        db.create_collection("execution_logs")
    except CollectionInvalid:
        pass
    db.execution_logs.create_index([("device_id", 1), ("created_at", -1)])
    db.execution_logs.create_index([("script", 1), ("action", 1)])
    try:
        db.execution_logs.create_index(
            "created_at", expireAfterSeconds=7776000
        )  # 90天
    except Exception as e:
        print(f"⚠️ execution_logs TTL 索引: {e}")
    print("✅ execution_logs 索引已创建")

    # capture_data（抓包用，可选）
    try:
        db.create_collection("capture_data")
    except CollectionInvalid:
        pass
    db.capture_data.create_index([("device_id", 1), ("timestamp", -1)])
    db.capture_data.create_index("package")
    try:
        db.capture_data.create_index(
            "timestamp", expireAfterSeconds=604800
        )  # 7天
    except Exception as e:
        print(f"⚠️ capture_data TTL 索引: {e}")
    print("✅ capture_data 索引已创建")

    # messages（消息持久化，可选）
    try:
        db.create_collection("messages")
    except CollectionInvalid:
        pass
    db.messages.create_index([("device_id", 1), ("created_at", -1)])
    db.messages.create_index([("platform", 1), ("direction", 1)])
    print("✅ messages 索引已创建")

    # api_keys（API 密钥管理，可选）
    try:
        db.create_collection("api_keys")
    except CollectionInvalid:
        pass
    db.api_keys.create_index("key", unique=True)
    db.api_keys.create_index("tenant_id")
    print("✅ api_keys 索引已创建")

    print("\n=== 数据库初始化完成 ===")


if __name__ == "__main__":
    init_database()
