import sqlite3
import os

DB_PATH = 'economy.db'

def run_migrations():
    if not os.path.exists(DB_PATH):
        print(f"Database {DB_PATH} not found!")
        return

    conn = sqlite3.connect(DB_PATH)
    cur = conn.cursor()

    # 1. Update USERS table (add username, avatar)
    print("Migrating USERS table...")
    try:
        cur.execute("ALTER TABLE users ADD COLUMN username TEXT")
        print("- Added 'username' column")
    except sqlite3.OperationalError:
        print("- 'username' column already exists")

    try:
        cur.execute("ALTER TABLE users ADD COLUMN avatar TEXT")
        print("- Added 'avatar' column")
    except sqlite3.OperationalError:
        print("- 'avatar' column already exists")

    # 2. Create LISTINGS table
    print("Creating LISTINGS table...")
    cur.execute("""
        CREATE TABLE IF NOT EXISTS listings (
            listing_id INTEGER PRIMARY KEY AUTOINCREMENT,
            card_id INTEGER NOT NULL,
            seller_id INTEGER NOT NULL,
            price INTEGER NOT NULL,
            created_at INTEGER NOT NULL,
            FOREIGN KEY(card_id) REFERENCES cards(card_id),
            FOREIGN KEY(seller_id) REFERENCES users(user_id)
        )
    """)
    print("- LISTINGS table verified")

    conn.commit()
    conn.close()
    print("Migration complete.")

if __name__ == '__main__':
    run_migrations()
