import sqlite3

#nonces and messanges
from .messages_long import MESSAGES as MESSAGES_LONG
from .nonces_2 import NONCES

import argparse
parser = argparse.ArgumentParser(description="populate sql db")
parser.add_argument("--database_path",type=str,default="./nonceANDmessage.db")
args, unknown_args = parser.parse_known_args()

class NonceMessageDB:
    def __init__(self, db_path="nonce_messages.db"):
        self.db_path = db_path
        self.conn = None
        self.init_db()
    
    def init_db(self):
        """Create table and index if they don't exist"""
        with sqlite3.connect(self.db_path) as conn:
            conn.execute("""
                CREATE TABLE IF NOT EXISTS messages (
                    nonce BLOB NOT NULL,
                    message BLOB NOT NULL
                )
            """)
            # Create index on nonce column
            conn.execute("CREATE INDEX IF NOT EXISTS idx_nonce ON messages(nonce)")
            conn.commit()
    
    def open_connection(self):
        """Open persistent connection for iteration"""
        if self.conn is None:
            self.conn = sqlite3.connect(self.db_path)
    
    def close_connection(self):
        """Close persistent connection"""
        if self.conn:
            self.conn.close()
            self.conn = None
    
    def insert(self, nonce, message):
        """Insert a nonce-message pair (hex strings converted to BLOB)"""
        with sqlite3.connect(self.db_path) as conn:
            nonce_blob = nonce
            message_blob = message
            conn.execute("INSERT INTO messages (nonce, message) VALUES (?, ?)", 
                        (nonce_blob, message_blob))
            conn.commit()
    
    def iterate_all(self):
        """Iterate over all nonce-message pairs using persistent connection"""
        self.open_connection()
        cursor = self.conn.execute("SELECT nonce, message FROM messages")
        for nonce_blob, message_blob in cursor:
            yield nonce_blob, message_blob
        # Note: Connection stays open for potential future iterations

# populate
if __name__ == "__main__":
    db = NonceMessageDB(db_path=args.database_path)
    for nonce, message in enumerate(NONCES,MESSAGES_LONG):
        db.insert(nonce,message)

