import os
import sqlite3  # SQLite module
import datetime
from .data import Datadb  # Corrected import

class Logsdb:
    """
    Database to store scraper logs.
    """
    def __init__(self, db_name="logs.db"):  # Updated db name
        db_folder = "data"  # Set the database folder
        os.makedirs(db_folder, exist_ok=True)
        self.db_name = os.path.join(db_folder, db_name)
        self.create_table()

    def log(self, message):
        """Logs a message into the database with the correct timestamp."""
        local_time = datetime.datetime.now().strftime("%Y-%m-%d %H:%M:%S")
        print(f"{local_time} {message}")  # ✅ Print log for debugging
        with sqlite3.connect(self.db_name) as conn:
            cursor = conn.cursor()
            cursor.execute("INSERT INTO logs (timestamp, message) VALUES (?, ?)", (local_time, message))
            conn.commit()

    def log_message(self, message):
        """
        Log a message into the database with the correct local timestamp.
        """
        local_time = datetime.datetime.now().strftime("%Y-%m-%d %H:%M:%S")  # ✅ Get local system time
        print(f"{local_time} {message}")  # ✅ Debug output
        self.execute_query("INSERT INTO logs (timestamp, message) VALUES (?, ?)", (local_time, message), commit=True)

    def execute_query(self, query, params=(), commit=False, fetch=False):
        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_table(self):
        """
        Create the logs table if it does not exist.
        """
        self.execute_query("""
            CREATE TABLE IF NOT EXISTS logs (
                id INTEGER PRIMARY KEY AUTOINCREMENT,
                timestamp TEXT NOT NULL,
                message TEXT NOT NULL
            )
        """, commit=True)

# ✅ Initialize databases **AFTER ensuring the table exists**
airdrop_db = Datadb()  # Corrected class name
log_db = Logsdb()
log_db.log_message("🚀 [INFO] Scraper logs database initialized.")

def scrape_site(url, keywords=["airdrop", "claim", "mint"]):
    """
    Scrapes a given site and stores data in the database.
    Logs AI Agent decisions and behavior as well.
    """
    log_db.log_message(f"🌐 [INFO] Starting scrape for {url}")
    try:
        log_db.log_message(f"🤖 [AI] Pre-scanning website structure for {url}")
        ai_decision = "Static Scraping Chosen"
        log_db.log_message(f"🤖 [AI] Decision: {ai_decision}")

        log_db.log_message(f"🔍 [AI] Validating extracted data from {url}")
        validation_passed = True  # Simulated result

        if validation_passed:
            log_db.log_message(f"✅ [AI] Data validation successful for {url}")
        else:
            log_db.log_message(f"⚠️ [AI] Data validation failed, triggering re-scrape for {url}")
            scrape_site(url)  # Recursive re-run
            return

        # Simulated scraping logic
        extracted_data = [
            {"name": "Example Airdrop", "claim_link": url, "mint_date": "2025-02-18", "mint_price": "Free",
             "discord": "N/A", "twitter": "N/A", "website": url, "ai_confidence": 0.9}
        ]

        log_db.log_message(f"📊 [AI] Extracted {len(extracted_data)} potential entries")

        for data in extracted_data:
            airdrop_db.insert_airdrop(
                source=url, name=data["name"], claim_link=data["claim_link"], mint_date=data["mint_date"],
                mint_price=data["mint_price"], discord=data["discord"], twitter=data["twitter"],
                website=data["website"], ai_confidence=data["ai_confidence"]
            )
            log_db.log_message(f"✅ [SUCCESS] Inserted airdrop: {data['name']}")
    except Exception as e:
        log_db.log_message(f"❌ [ERROR] Failed to scrape {url}: {e}")
        log_db.log_message(f"🛠️ [AI] Manual intervention required for {url}")
    finally:
        log_db.log_message(f"🏁 [INFO] Scraping complete for {url}")

# ✅ Start logging **AFTER ensuring everything is set up**
log_db.log_message("🚀 [INFO] Scraping Airdrops...")
scrape_site("https://example.com/airdrop")
log_db.log_message("✅ [INFO] Scraping Done")
