import sqlite3
import os
from cryptography.fernet import Fernet
import hashlib
import base64
import json
import time

class WalletDB:
    def __init__(self, data_dir=None):
        self.data_dir = data_dir or os.path.expanduser("~/.lunawallet")
        os.makedirs(self.data_dir, exist_ok=True)
        self.db_path = os.path.join(self.data_dir, "wallets.db")
        print(f"[WalletDB] data_dir: {self.data_dir}")
        print(f"[WalletDB] db_path: {self.db_path}")
        self.conn = sqlite3.connect(self.db_path)
        self._init_db()

    def _init_db(self):
        c = self.conn.cursor()
        c.execute('''CREATE TABLE IF NOT EXISTS wallets (
            address TEXT PRIMARY KEY,
            label TEXT,
            public_key TEXT,
            encrypted_private_key BLOB,
            is_locked INTEGER,
            created REAL,
            balance REAL,
            available_balance REAL
        )''')
        self.conn.commit()

    def save_wallet(self, address, label, public_key, encrypted_private_key, is_locked, created, balance, available_balance):
        c = self.conn.cursor()
        c.execute('''REPLACE INTO wallets (address, label, public_key, encrypted_private_key, is_locked, created, balance, available_balance)
            VALUES (?, ?, ?, ?, ?, ?, ?, ?)''',
            (address, label, public_key, encrypted_private_key, int(is_locked), created, balance, available_balance))
        self.conn.commit()

    def load_wallet(self, address):
        c = self.conn.cursor()
        c.execute('SELECT * FROM wallets WHERE address=?', (address,))
        row = c.fetchone()
        if row:
            return {
                'address': row[0],
                'label': row[1],
                'public_key': row[2],
                'encrypted_private_key': row[3],
                'is_locked': bool(row[4]),
                'created': row[5],
                'balance': row[6],
                'available_balance': row[7],
            }
        return None

    def list_wallets(self):
        c = self.conn.cursor()
        c.execute('SELECT address, label, is_locked, balance, available_balance FROM wallets')
        return c.fetchall()

    def close(self):
        self.conn.close()

# Example usage:
if __name__ == "__main__":
    db = WalletDB()
    print("Wallets:", db.list_wallets())
    db.close()
