"""v7: 用户记忆拆分、auto_save 清理、踩坑迁移、archive embedding"""
import json
from datetime import datetime
from szyjiyi.config import USER_SCOPE_DIR
from szyjiyi.db.schema import USER_MEMORIES_TABLE, VEC_USER_MEMORIES_TABLE, VEC_ISSUES_ARCHIVE_TABLE
from szyjiyi.log import log


def upgrade(conn, engine=None, **_):
    conn.execute(USER_MEMORIES_TABLE)
    conn.execute(VEC_USER_MEMORIES_TABLE)
    
    user_rows = conn.execute("SELECT * FROM memories WHERE project_dir=?", (USER_SCOPE_DIR,)).fetchall()
    if user_rows:
        for row in user_rows:
            conn.execute(
                "INSERT INTO user_memories (id, content, tags, scope, source, session_id, created_at, updated_at) "
                "VALUES (?,?,?,?,?,?,?,?)",
                (row["id"], row["content"], row["tags"], row["scope"], row["source"],
                 row["session_id"], row["created_at"], row["updated_at"])
            )
            vec_row = conn.execute("SELECT rowid, embedding FROM vec_memories WHERE rowid=(SELECT rowid FROM memories WHERE id=?)", (row["id"],)).fetchone()
            if vec_row:
                conn.execute("INSERT INTO vec_user_memories (rowid, embedding) VALUES (?,?)",
                           (vec_row["rowid"], vec_row["embedding"]))
        conn.execute("DELETE FROM memories WHERE project_dir=?", (USER_SCOPE_DIR,))
        log.info("v7 migration: moved %d user memories to user_memories table", len(user_rows))

    auto_save_rows = conn.execute("SELECT id FROM memories WHERE source='auto_save'").fetchall()
    if auto_save_rows:
        conn.execute("DELETE FROM memories WHERE source='auto_save'")
        log.info("v7 migration: deleted %d auto_save memories", len(auto_save_rows))

    pitfall_rows = conn.execute("SELECT * FROM memories WHERE tags LIKE '%\"踩坑\"%'").fetchall()
    if pitfall_rows:
        now = datetime.now().astimezone().isoformat()
        for row in pitfall_rows:
            existing = conn.execute(
                "SELECT id FROM issues WHERE project_dir=? AND memory_id=?",
                (row["project_dir"], row["id"])
            ).fetchone()
            if existing:
                continue
            next_num_row = conn.execute(
                "SELECT MAX(issue_number) as m FROM issues WHERE project_dir=?",
                (row["project_dir"],)
            ).fetchone()
            next_num = (next_num_row["m"] or 0) + 1
            issue_id = f"issue-{next_num}"
            conn.execute(
                "INSERT INTO issues (id, project_dir, issue_number, date, title, description, status, memory_id, created_at, updated_at) "
                "VALUES (?,?,?,?,?,?,?,?,?,?)",
                (issue_id, row["project_dir"], next_num, now[:10], row["content"][:100],
                 row["content"], "pending", row["id"], now, now)
            )
        log.info("v7 migration: migrated %d pitfall memories to issues", len(pitfall_rows))

    conn.execute(VEC_ISSUES_ARCHIVE_TABLE)
    archive_count = conn.execute("SELECT COUNT(*) as c FROM issues_archive").fetchone()["c"]
    if archive_count > 0 and archive_count <= 50 and engine:
        gen_count = 0
        for row in conn.execute("SELECT rowid, title, description FROM issues_archive").fetchall():
            text = f"{row['title']}\n{row['description']}"
            emb = engine.encode(text)
            emb_blob = json.dumps(emb).encode("utf-8")
            conn.execute("INSERT INTO vec_issues_archive (rowid, embedding) VALUES (?,?)", (row["rowid"], emb_blob))
            gen_count += 1
        log.info("v7 migration: generated embeddings for %d archived issues", gen_count)
    elif archive_count > 50:
        log.info("v7 migration: skipped embedding generation for %d archived issues (>50, lazy loading)", archive_count)
