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

/**
 * Test configuration loaded from .env file
 */
export interface TestConfig {
  serverUrl: string;
  serverName: string;
  username: string;
  password: string;
  musicLibraryId?: string;
  movieLibraryId?: string;
  artistId?: string;
  albumId?: string;
  trackId?: string;
  movieId?: string;
  episodeId?: string;
  timeout: number;
  waitTimeout: number;
}

/**
 * Load test configuration from .env file
 * Falls back to demo server if .env doesn't exist
 */
export function loadTestConfig(): TestConfig {
  const envPath = path.join(__dirname, "..", ".env");
  const config: TestConfig = {
    serverUrl: "https://demo.jellyfin.org/stable",
    serverName: "Demo Server",
    username: "demo",
    password: "",
    timeout: 60000,
    waitTimeout: 15000,
  };

  // Try to load .env file
  if (fs.existsSync(envPath)) {
    const envContent = fs.readFileSync(envPath, "utf-8");
    const lines = envContent.split("\n");

    for (const line of lines) {
      // Skip comments and empty lines
      if (line.trim().startsWith("#") || !line.trim()) continue;

      const [key, ...valueParts] = line.split("=");
      const value = valueParts.join("=").trim();

      switch (key.trim()) {
        case "TEST_SERVER_URL":
          if (value) config.serverUrl = value;
          break;
        case "TEST_SERVER_NAME":
          if (value) config.serverName = value;
          break;
        case "TEST_USERNAME":
          if (value) config.username = value;
          break;
        case "TEST_PASSWORD":
          config.password = value; // Can be empty
          break;
        case "TEST_MUSIC_LIBRARY_ID":
          if (value) config.musicLibraryId = value;
          break;
        case "TEST_MOVIE_LIBRARY_ID":
          if (value) config.movieLibraryId = value;
          break;
        case "TEST_ARTIST_ID":
          if (value) config.artistId = value;
          break;
        case "TEST_ALBUM_ID":
          if (value) config.albumId = value;
          break;
        case "TEST_TRACK_ID":
          if (value) config.trackId = value;
          break;
        case "TEST_MOVIE_ID":
          if (value) config.movieId = value;
          break;
        case "TEST_EPISODE_ID":
          if (value) config.episodeId = value;
          break;
        case "TEST_TIMEOUT":
          if (value) config.timeout = parseInt(value, 10);
          break;
        case "TEST_WAIT_TIMEOUT":
          if (value) config.waitTimeout = parseInt(value, 10);
          break;
      }
    }
  } else {
    console.warn(
      "⚠️  No e2e/.env file found. Using demo server credentials."
    );
    console.warn(
      "   Copy e2e/.env.example to e2e/.env and configure your test server."
    );
  }

  return config;
}

// Export a singleton instance
export const testConfig = loadTestConfig();
