"""检查 memory.db 中 project_dir 分布，排查 Web 看板 0 个项目问题"""
import sqlite3
from pathlib import Path

db_path = Path.home() / ".devmemory" / "memory.db"
print(f"数据库路径: {db_path}")
print(f"文件存在: {db_path.exists()}")

if not db_path.exists():
    print("数据库不存在，退出")
    exit()

conn = sqlite3.connect(str(db_path))
conn.row_factory = sqlite3.Row

# 1. 总记忆数
total = conn.execute("SELECT COUNT(*) as cnt FROM memories").fetchone()["cnt"]
print(f"\n总记忆数: {total}")

# 2. 按 project_dir 分组
rows = conn.execute("SELECT project_dir, scope, COUNT(*) as cnt FROM memories GROUP BY project_dir, scope").fetchall()
print(f"\n按 project_dir + scope 分组:")
for r in rows:
    pd = r["project_dir"] or "(空字符串)"
    print(f"  project_dir={pd}, scope={r['scope']}, count={r['cnt']}")

# 3. 按 project_dir 分组（不含 scope）
rows2 = conn.execute("SELECT project_dir, COUNT(*) as cnt FROM memories GROUP BY project_dir").fetchall()
print(f"\n按 project_dir 分组（get_projects SQL）:")
for r in rows2:
    pd = r["project_dir"] or "(空字符串)"
    empty = "← 会被 if not pd: continue 过滤" if not r["project_dir"] else ""
    print(f"  project_dir={pd}, count={r['cnt']} {empty}")

# 4. 模拟 get_projects 逻辑
projects = {}
for r in rows2:
    pd = r["project_dir"]
    if not pd:
        continue
    projects[pd] = r["cnt"]
print(f"\nget_projects 返回的项目数: {len(projects)}")
for pd, cnt in projects.items():
    print(f"  {pd}: {cnt} 条记忆")

conn.close()
