part of '../../core_app.dart';

const String _defaultInitialUrl = 'http://xszy.lzzneng.com/login.html';

late Uri _initialUri;
late String _initialUrl;

void _initializeUrls() {
  final candidate = (_env.initialUrl ?? '').trim();
  if (candidate.isEmpty) {
    _initialUri = Uri.parse(_defaultInitialUrl);
  } else {
    final directUri = Uri.tryParse(candidate);
    if (directUri != null && directUri.hasScheme) {
      _initialUri = directUri;
    } else if (candidate.startsWith('//')) {
      final protocolRelativeUri = Uri.tryParse('https:$candidate');
      if (protocolRelativeUri != null && protocolRelativeUri.hasScheme) {
        _initialUri = protocolRelativeUri;
      }
    } else {
      final httpsUri = Uri.tryParse('https://$candidate');
      if (httpsUri != null && httpsUri.hasScheme && httpsUri.host.isNotEmpty) {
        _initialUri = httpsUri;
      } else {
        _initialUri = Uri.parse(_defaultInitialUrl);
      }
    }
  }
  _initialUrl = _initialUri.toString();
}

bool _isNetworkUrl(String? url) {
  final uri = Uri.tryParse(url ?? '');
  if (uri == null) {
    return false;
  }
  return uri.scheme == 'http' || uri.scheme == 'https';
}

String _normalizeComparableUri(Uri uri) {
  final scheme = uri.scheme.toLowerCase();
  final host = uri.host.toLowerCase();
  final port = uri.hasPort ? uri.port : _defaultPortForScheme(scheme);
  final path = _normalizeComparablePath(uri.path);
  final query = uri.query;
  return '$scheme://$host:$port$path?$query';
}

int _defaultPortForScheme(String scheme) {
  return switch (scheme) {
    'https' => 443,
    'http' => 80,
    _ => -1,
  };
}

String _normalizeComparablePath(String path) {
  if (path.isEmpty) {
    return '/';
  }
  if (path.length > 1 && path.endsWith('/')) {
    return path.substring(0, path.length - 1);
  }
  return path;
}
