#!/usr/bin/env python3
"""持久对话会话 → MongoDB karuo_site.持久对话会话（本地 ~/.persistent-chat-local/sessions.json）"""
import json
import os
import sys
from datetime import datetime, timezone

HOME = os.path.expanduser("~")
SESSIONS_FILE = os.path.join(HOME, ".persistent-chat-local", "sessions.json")
MONGO_URI = os.environ.get("MONGO_URI", "mongodb://127.0.0.1:27017")
DB_NAME = os.environ.get("MONGO_DB", "karuo_site")
COLL_NAME = "持久对话会话"


def main() -> int:
    if not os.path.isfile(SESSIONS_FILE):
        print("SKIP: no sessions.json")
        return 0
    try:
        from pymongo import MongoClient
    except ImportError:
        print("SKIP: pymongo not installed (pip3 install pymongo)")
        return 0

    with open(SESSIONS_FILE, encoding="utf-8") as f:
        data = json.load(f)

    client = MongoClient(MONGO_URI, serverSelectionTimeoutMS=4000)
    client.admin.command("ping")
    col = client[DB_NAME][COLL_NAME]
    col.create_index("token", unique=True)
    col.create_index("workspace")
    col.create_index("lastActiveAt")

    now = datetime.now(timezone.utc)
    n = 0
    for token, sess in data.items():
        doc = dict(sess)
        doc["token"] = token
        doc["mongo_sync_at"] = now
        col.update_one({"token": token}, {"$set": doc}, upsert=True)
        n += 1
    print(f"OK: synced {n} sessions → {DB_NAME}.{COLL_NAME}")
    return 0


if __name__ == "__main__":
    try:
        sys.exit(main())
    except Exception as e:
        print(f"FAIL: {e}", file=sys.stderr)
        sys.exit(1)
