"""v1: memories 加 project_dir；旧版 issues archived 记录迁移到 issues_archive"""


def upgrade(conn, **_):
    cols = {row[1] for row in conn.execute("PRAGMA table_info(memories)").fetchall()}
    if "project_dir" not in cols:
        conn.execute("ALTER TABLE memories ADD COLUMN project_dir TEXT NOT NULL DEFAULT ''")
    issue_cols = {row[1] for row in conn.execute("PRAGMA table_info(issues)").fetchall()}
    if "status" not in issue_cols:
        return
    archived = conn.execute("SELECT * FROM issues WHERE status='archived'").fetchall()
    if archived:
        for row in archived:
            conn.execute(
                "INSERT INTO issues_archive (id, project_dir, issue_number, date, title, status, content, created_at, updated_at) "
                "VALUES (?,?,?,?,?,?,?,?,?)",
                (row["id"], row["project_dir"], row["issue_number"], row["date"], row["title"],
                 row["status"], row["content"], row["created_at"], row["updated_at"])
            )
        conn.execute("DELETE FROM issues WHERE status='archived'")
        conn.execute("CREATE TABLE issues_new AS SELECT id, project_dir, issue_number, date, title, content, created_at, updated_at FROM issues WHERE 1=0")
        conn.execute("INSERT INTO issues_new SELECT id, project_dir, issue_number, date, title, status, content, created_at, updated_at FROM issues")
        conn.execute("DROP TABLE issues")
        conn.execute("ALTER TABLE issues_new RENAME TO issues")
