<?php

declare(strict_types=1);

namespace Drupal\native_observability_report\Service;

use Drupal\Core\Site\Settings;

/**
 * Resolves the current execution environment for reporting purposes.
 */
final class ObservabilityEnvironmentResolver {

  /**
   * Returns the normalized environment key.
   */
  public function resolve(): string {
    $settingsEnvironment = strtolower((string) Settings::get('native_observability_environment', ''));
    if ($settingsEnvironment !== '') {
      return $this->normalizeEnvironment($settingsEnvironment);
    }

    $environmentVariables = [
      getenv('NATIVE_OBSERVABILITY_ENV') ?: '',
      getenv('DRUPAL_ENV') ?: '',
      getenv('APP_ENV') ?: '',
      getenv('DDEV_PRIMARY_URL') ? 'dev' : '',
    ];

    foreach ($environmentVariables as $environmentVariable) {
      $environmentVariable = strtolower(trim((string) $environmentVariable));
      if ($environmentVariable !== '') {
        return $this->normalizeEnvironment($environmentVariable);
      }
    }

    $containerYamls = Settings::get('container_yamls', []);
    if (is_array($containerYamls)) {
      foreach ($containerYamls as $containerYaml) {
        $containerYaml = strtolower((string) $containerYaml);
        if (str_contains($containerYaml, 'development.services.yml')) {
          return 'dev';
        }
      }
    }

    return 'prod';
  }

  /**
   * Returns whether the active environment should be treated as production.
   */
  public function isProduction(): bool {
    return $this->resolve() === 'prod';
  }

  /**
   * Normalizes an environment string to a supported internal key.
   */
  private function normalizeEnvironment(string $environment): string {
    $environment = strtolower(trim($environment));

    return match ($environment) {
      'prod', 'production' => 'prod',
      'dev', 'development', 'local', 'test', 'testing', 'ddev' => 'dev',
      default => $environment !== '' ? $environment : 'prod',
    };
  }

}
