/// Endpoint/transport configuration for proto-socket connections.
///
/// Pure value object. No network I/O, no Flutter binding dependencies — safe
/// to construct from app bootstrap or unit tests.
class ProtoSocketEndpointConfig {
  static const String defaultPath = '/';
  static const int defaultHeartbeatIntervalSeconds = 30;
  static const int defaultHeartbeatWaitSeconds = 60;

  final String host;
  final int port;
  final bool secure;
  final String path;
  final int heartbeatIntervalSeconds;
  final int heartbeatWaitSeconds;
  final bool enabled;

  const ProtoSocketEndpointConfig({
    required this.host,
    required this.port,
    required this.secure,
    this.path = defaultPath,
    this.heartbeatIntervalSeconds = defaultHeartbeatIntervalSeconds,
    this.heartbeatWaitSeconds = defaultHeartbeatWaitSeconds,
    this.enabled = false,
  });

  /// Build a config from a flat string map (e.g. dart-define / env).
  ///
  /// `host` is required; everything else falls back to defaults.
  /// Returns null when `host` is absent or empty so callers can treat the
  /// integration as disabled.
  static ProtoSocketEndpointConfig? fromEnv(Map<String, String> env) {
    final host = env['PROTO_SOCKET_HOST']?.trim();
    if (host == null || host.isEmpty) {
      return null;
    }

    final secure = _parseBool(env['PROTO_SOCKET_SECURE']) ?? false;
    final port = _parseInt(env['PROTO_SOCKET_PORT']) ?? (secure ? 443 : 80);
    final path = _normalizePath(env['PROTO_SOCKET_PATH']);
    final heartbeatInterval =
        _parseInt(env['PROTO_SOCKET_HEARTBEAT_INTERVAL_SECONDS']) ??
        defaultHeartbeatIntervalSeconds;
    final heartbeatWait =
        _parseInt(env['PROTO_SOCKET_HEARTBEAT_WAIT_SECONDS']) ??
        defaultHeartbeatWaitSeconds;
    final enabled = _parseBool(env['PROTO_SOCKET_ENABLED']) ?? false;

    return ProtoSocketEndpointConfig(
      host: host,
      port: port,
      secure: secure,
      path: path,
      heartbeatIntervalSeconds: heartbeatInterval,
      heartbeatWaitSeconds: heartbeatWait,
      enabled: enabled,
    );
  }

  String get scheme => secure ? 'wss' : 'ws';

  Uri toUri() => Uri(scheme: scheme, host: host, port: port, path: path);

  static String _normalizePath(String? raw) {
    final value = raw?.trim();
    if (value == null || value.isEmpty) return defaultPath;
    return value.startsWith('/') ? value : '/$value';
  }

  static int? _parseInt(String? raw) {
    final value = raw?.trim();
    if (value == null || value.isEmpty) return null;
    return int.tryParse(value);
  }

  static bool? _parseBool(String? raw) {
    final value = raw?.trim().toLowerCase();
    if (value == null || value.isEmpty) return null;
    if (value == 'true' || value == '1' || value == 'yes') return true;
    if (value == 'false' || value == '0' || value == 'no') return false;
    return null;
  }
}
