// @category _Reman3
// @menupath Reman3.Test

import ghidra.app.script.GhidraScript;
import ghidra.program.model.address.Address;
import ghidra.program.model.data.DataType;
import ghidra.program.model.data.StandAloneDataTypeManager;
import re3lib.RecompileConfig;

import java.io.File;
import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
import java.nio.file.Files;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

// SQLite imports
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;

public class Test extends GhidraScript {
  // Will rebuild all functions
  public boolean rebuildAllGlobals = true;
  FunctionDatabase functionDB;

  @Override
  public void run() throws Exception {
    RecompileConfig.INSTANCE = new RecompileConfig(this);
    
    // Example SQLite usage
    testSQLite();
  }
  
  private void testSQLite() throws Exception {
    String dbPath = "jdbc:sqlite:" + RecompileConfig.INSTANCE.outputDir + "/functions.db";
    
    try (Connection conn = DriverManager.getConnection(dbPath)) {
      println("Connected to SQLite database: " + dbPath);
      
      // Create a simple table
      try (Statement stmt = conn.createStatement()) {
        stmt.execute("CREATE TABLE IF NOT EXISTS functions (" +
                    "id INTEGER PRIMARY KEY AUTOINCREMENT, " +
                    "address TEXT NOT NULL, " +
                    "name TEXT NOT NULL, " +
                    "file_path TEXT)");
        println("Functions table created/verified");
      }
      
      // Insert example data
      String insertSQL = "INSERT INTO functions (address, name, file_path) VALUES (?, ?, ?)";
      try (PreparedStatement pstmt = conn.prepareStatement(insertSQL)) {
        pstmt.setString(1, "0x00401000");
        pstmt.setString(2, "main");
        pstmt.setString(3, "/path/to/main.cxx");
        pstmt.executeUpdate();
        println("Inserted example function");
      }
      
      // Query data
      try (Statement stmt = conn.createStatement();
           ResultSet rs = stmt.executeQuery("SELECT * FROM functions")) {
        while (rs.next()) {
          println("Function: " + rs.getString("name") + 
                 " at " + rs.getString("address") + 
                 " in " + rs.getString("file_path"));
        }
      }
      
    } catch (SQLException e) {
      println("SQLite error: " + e.getMessage());
      throw e;
    }
  }

  private void scanDirectory(File directory, FunctionDatabase.Type type) throws Exception {
    File[] files = directory.listFiles((dir, name) -> name.endsWith(".cxx"));
    if (files == null)
      return;

    for (File file : files) {
      scanFile(file, type);
    }
  }
}