from pathlib import Path
import sqlite3

def fix_sessions(folder_path: Path):
    for session_file in folder_path.glob("*.session"):
        print(f"\nProcessing: {session_file}")

        try:
            conn = sqlite3.connect(session_file)
            cur = conn.cursor()

            cur.execute(
                "SELECT name FROM sqlite_master WHERE type='table' AND name='sessions';"
            )
            if not cur.fetchone():
                print(" - sessions table not found, skipping")
                conn.close()
                continue

            cur.execute("PRAGMA table_info(sessions);")
            columns = [row[1] for row in cur.fetchall()]

            if "tmp_auth_key" not in columns:
                print(" - tmp_auth_key column not found, skipping")
                conn.close()
                continue

            try:
                cur.execute("ALTER TABLE sessions DROP COLUMN tmp_auth_key;")
                print(" - tmp_auth_key column removed")
            except Exception as e:
                print(" - error removing tmp_auth_key:", e)

            try:
                cur.execute("UPDATE version SET version = 7 WHERE version != 7;")
                if cur.rowcount:
                    print(" - version updated to 7")
                else:
                    print(" - version already 7")
            except Exception as e:
                print(" - version table not found or update failed:", e)

            conn.commit()
            conn.close()

        except Exception as e:
            print("Error processing file:", e)

    print("\nDone")


if __name__ == "__main__":
    folder_input = input("Enter folder path: ").strip()
    folder_path = Path(folder_input)

    if not folder_path.is_dir():
        print("Invalid path.")
    else:
        fix_sessions(folder_path)
