import { Environment } from "./service-factory";
import path from 'path';
import fs from 'fs';

export interface CognitoConfig {
  clientId: string;
  userPoolId: string;
  region: string;
  domain: string;
  clientSecret?: string;
  redirectUri: string;
  tokenEndpoint: string;
  userInfoEndpoint: string;
}

export interface PortalConfig {
  baseUrl: string;
  authentication: string;
  projects: string;
  teams: string;
  users: string;
}

let envLoaded = false;

function parseEnvFile(filePath: string): Record<string, string> {
  try {
    let content: string;
    try {
      content = fs.readFileSync(filePath, 'utf8');
    } catch {
      content = fs.readFileSync(filePath, 'utf16le');
    }
    content = content.replace(/\x00/g, '');
    const envVars: Record<string, string> = {};
    content.split(/\r?\n/).forEach(line => {
      line = line.trim();
      if (line && !line.startsWith('#')) {
        const [key, ...valueParts] = line.split('=');
        if (key && valueParts.length > 0) {
          envVars[key.trim()] = valueParts.join('=').trim();
        }
      }
    });
    return envVars;
  } catch (error) {
    console.log(`Failed to parse env file ${filePath}:`, error);
    return {};
  }
}

export const getCognitoConfig = (environment: Environment): CognitoConfig => {
  const cliPackageDir = path.dirname(require.main?.filename || __dirname);
  const envFilePath = path.join(path.dirname(cliPackageDir), `.env.${environment}`);
  if (fs.existsSync(envFilePath)) {
    const envVars = parseEnvFile(envFilePath);
    Object.entries(envVars).forEach(([key, value]) => {
      if (!process.env[key]) {
        process.env[key] = value;
      }
    });
  }
  const config = {
    clientId: process.env.COGNITO_CLIENT_ID!,
    userPoolId: process.env.COGNITO_USER_POOL_ID!,
    region: process.env.COGNITO_REGION!,
    domain: process.env.COGNITO_DOMAIN!,
    clientSecret: process.env.COGNITO_CLIENT_SECRET,
    redirectUri: process.env.COGNITO_REDIRECT_URI!,
    tokenEndpoint: process.env.COGNITO_TOKEN_ENDPOINT!,
    userInfoEndpoint: process.env.COGNITO_USER_INFO_ENDPOINT!
  };
  return config;
};

export const getPortalConfig = (environment: Environment): PortalConfig => {
  const cliPackageDir = path.dirname(require.main?.filename || __dirname);
  const envFilePath = path.join(path.dirname(cliPackageDir), `.env.${environment}`);
  if (fs.existsSync(envFilePath)) {
    const envVars = parseEnvFile(envFilePath);
    Object.entries(envVars).forEach(([key, value]) => {
      if (!process.env[key]) {
        process.env[key] = value;
      }
    });
  }
  const config = {
    baseUrl: process.env.PORTAL_BASE_URL!,
    authentication: process.env.PORTAL_AUTHENTICATION_ENDPOINT!,
    projects: process.env.PORTAL_PROJECTS_ENDPOINT!,
    teams: process.env.PORTAL_TEAMS_ENDPOINT!,
    users: process.env.PORTAL_USERS_ENDPOINT!
  };
  return config;
};