"""模拟另一台机器的场景：只有 auto_save 保存的记忆，验证 get_projects 是否返回 0"""
import sqlite3
import tempfile
import os
import sys
sys.path.insert(0, os.path.dirname(os.path.dirname(os.path.abspath(__file__))))

from devmemory.db import ConnectionManager, init_db
from devmemory.db.memory_repo import MemoryRepo
from devmemory.embedding.engine import EmbeddingEngine
from devmemory.tools.auto_save import handle_auto_save
from devmemory.web.api import get_projects

# 用临时数据库模拟干净环境
tmp = tempfile.mkdtemp()
db_path = os.path.join(tmp, "memory.db")
os.environ["DEVMEMORY_DB_PATH"] = db_path

# 模拟 MCP Server 启动时传了 --project-dir
cm = ConnectionManager(project_dir="/Users/macos/web/test")
init_db(cm.conn)
engine = EmbeddingEngine()

print(f"临时数据库: {db_path}")
print(f"cm.project_dir: {cm.project_dir}")

# 模拟 AI 调用 auto_save，只传 preferences（用户截图中的场景）
result1 = handle_auto_save(
    {"preferences": ["用户偏好测试1", "用户偏好测试2"], "scope": "project"},
    cm=cm, engine=engine, session_id=1
)
print(f"\nauto_save (只有 preferences): {result1}")

# 检查数据库
rows = cm.conn.execute("SELECT id, scope, project_dir, content FROM memories").fetchall()
print(f"\n数据库中的记忆 ({len(rows)} 条):")
for r in rows:
    print(f"  id={r['id']}, scope={r['scope']}, project_dir='{r['project_dir']}', content={r['content'][:30]}")

# 调用 get_projects
projects = get_projects(cm)
print(f"\nget_projects 返回: {projects}")
print(f"项目数: {len(projects['projects'])}")

# 再模拟传了 decisions 的情况
print("\n--- 再添加 decisions ---")
result2 = handle_auto_save(
    {"decisions": ["决策测试1"], "scope": "project"},
    cm=cm, engine=engine, session_id=2
)
print(f"auto_save (decisions): {result2}")

rows2 = cm.conn.execute("SELECT id, scope, project_dir, content FROM memories").fetchall()
print(f"\n数据库中的记忆 ({len(rows2)} 条):")
for r in rows2:
    print(f"  id={r['id']}, scope={r['scope']}, project_dir='{r['project_dir']}', content={r['content'][:30]}")

projects2 = get_projects(cm)
print(f"\nget_projects 返回: {projects2}")
print(f"项目数: {len(projects2['projects'])}")

cm.close()
# 清理环境变量
del os.environ["DEVMEMORY_DB_PATH"]
