import fs from "node:fs";
import path from "node:path";
import os from "node:os";

/**
 * Clears the JellyTau database and cache before tests
 * This ensures each test run starts with a fresh state
 */
export function clearAppData() {
  const appDataDir = path.join(
    os.homedir(),
    ".local/share/com.dtourolle.jellytau"
  );

  try {
    if (fs.existsSync(appDataDir)) {
      // Remove database file
      const dbPath = path.join(appDataDir, "jellytau.db");
      if (fs.existsSync(dbPath)) {
        fs.unlinkSync(dbPath);
        console.log("Cleared test database");
      }

      // Clear any cache files if needed
      // Add more cleanup as needed
    }
  } catch (error) {
    console.warn("Failed to clear app data:", error);
    // Don't fail tests if cleanup fails
  }
}

/**
 * Wait for element with retries
 * Useful for elements that might take time to appear
 */
export async function waitForElement(
  selector: string,
  timeout: number = 15000,
  retries: number = 3
): Promise<WebdriverIO.Element> {
  for (let i = 0; i < retries; i++) {
    try {
      const element = await $(selector);
      await element.waitForDisplayed({ timeout });
      return element;
    } catch (error) {
      if (i === retries - 1) throw error;
      await browser.pause(1000);
    }
  }
  throw new Error(`Element ${selector} not found after ${retries} retries`);
}
