import os
import sqlite3  # SQLite module
import csv
import json


class Datadb:
    """
    SQLite database handler for storing airdrop information, tokens, and NFTs.
    """

    def __init__(self, db_name="data.db"):
        """Initialize the database connection and ensure tables exist."""
        db_folder = "data"  # Ensure the 'data' directory exists
        os.makedirs(db_folder, exist_ok=True)
        self.db_name = os.path.join(db_folder, db_name)
        self.create_tables()  # ✅ Ensure tables are created upon initialization

    def execute_query(self, query, params=(), commit=False, fetch=False):
        """Execute a query safely with optional commit and fetch."""
        with sqlite3.connect(self.db_name) as conn:
            cursor = conn.cursor()
            cursor.execute(query, params)
            if commit:
                conn.commit()
            if fetch:
                return cursor.fetchall()

    def create_tables(self):
        """Create the necessary tables if they do not exist."""
        # ✅ Create 'airdrops' table
        self.execute_query("""
            CREATE TABLE IF NOT EXISTS airdrops (
                id INTEGER PRIMARY KEY AUTOINCREMENT,
                source TEXT NOT NULL,
                name TEXT UNIQUE NOT NULL,
                claim_link TEXT,
                mint_date TEXT,
                mint_price TEXT,
                discord TEXT,
                twitter TEXT,
                website TEXT,
                timestamp TIMESTAMP DEFAULT CURRENT_TIMESTAMP NOT NULL,
                ai_confidence REAL
            )
        """, commit=True)

        # ✅ Create 'tokens' table
        self.execute_query("""
            CREATE TABLE IF NOT EXISTS tokens (
                id INTEGER PRIMARY KEY AUTOINCREMENT,
                name TEXT UNIQUE NOT NULL,
                symbol TEXT UNIQUE NOT NULL,
                contract_address TEXT UNIQUE,
                market_cap REAL,
                token_price REAL,
                timestamp TIMESTAMP DEFAULT CURRENT_TIMESTAMP NOT NULL
            )
        """, commit=True)

        # ✅ Create 'nfts' table
        self.execute_query("""
            CREATE TABLE IF NOT EXISTS nfts (
                id INTEGER PRIMARY KEY AUTOINCREMENT,
                name TEXT UNIQUE NOT NULL,
                collection TEXT NOT NULL,
                mint_price TEXT,
                mint_date TEXT,
                blockchain TEXT,
                timestamp TIMESTAMP DEFAULT CURRENT_TIMESTAMP NOT NULL
            )
        """, commit=True)

        print("✅ All required tables created (if they didn't exist).")

    def insert_airdrop(self, source, name, claim_link, mint_date, mint_price, discord, twitter, website, ai_confidence):
        """Insert a new airdrop entry into the database only if it doesn't already exist."""
        existing_entry = self.execute_query(
            "SELECT id FROM airdrops WHERE name = ? AND source = ?",
            (name, source),
            fetch=True
        )

        if existing_entry:
            print(f"⚠️ Airdrop '{name}' already exists. Skipping insertion.")
        else:
            self.execute_query("""
                INSERT INTO airdrops (source, name, claim_link, mint_date, mint_price, discord, twitter, website, ai_confidence)
                VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)
            """, (source, name, claim_link, mint_date, mint_price, discord, twitter, website, ai_confidence), commit=True)
            print(f"✅ Airdrop '{name}' inserted successfully.")

    def entry_exists(self, table, column, value):
        """Check if a specific entry exists in a given table and column."""
        query = f"SELECT COUNT(*) FROM {table} WHERE {column} = ?"
        result = self.execute_query(query, (value,), fetch=True)
        return result[0][0] > 0  # Returns True if entry exists, False otherwise

    def export_to_csv(self, table_name, filename):
        """Export all table data to a CSV file."""
        rows = self.execute_query(f"SELECT * FROM {table_name}", fetch=True)

        if not rows:
            print(f"⚠️ No data found in {table_name}. Skipping CSV export.")
            return

        headers = [description[0] for description in self.execute_query(f"PRAGMA table_info({table_name})", fetch=True)]

        with open(filename, mode="w", newline="", encoding="utf-8") as file:
            writer = csv.writer(file)
            writer.writerow(headers)
            writer.writerows(rows)

        print(f"✅ {table_name} data exported to {filename}")

    def export_to_json(self, table_name, filename):
        """Export all table data to a JSON file."""
        rows = self.execute_query(f"SELECT * FROM {table_name}", fetch=True)

        if not rows:
            print(f"⚠️ No data found in {table_name}. Skipping JSON export.")
            return

        headers = [description[0] for description in self.execute_query(f"PRAGMA table_info({table_name})", fetch=True)]

        data = [dict(zip(headers, row)) for row in rows]

        with open(filename, mode="w", encoding="utf-8") as file:
            json.dump(data, file, indent=4)

        print(f"✅ {table_name} data exported to {filename}")

# ✅ Initialize database when the script is run directly
if __name__ == "__main__":
    db = Datadb()
    db.create_tables()

    print("\n🔍 Checking Stored Airdrops:")
    db.export_to_csv("airdrops", "airdrops.csv")
    db.export_to_json("airdrops", "airdrops.json")

    print("\n🔍 Checking Stored Tokens:")
    db.export_to_csv("tokens", "tokens.csv")
    db.export_to_json("tokens", "tokens.json")

    print("\n🔍 Checking Stored NFTs:")
    db.export_to_csv("nfts", "nfts.csv")
    db.export_to_json("nfts", "nfts.json")
