import 'package:shared_preferences/shared_preferences.dart';

class AppConstants {
  static const String _serverUrlKey = 'server_base_url';
  static const String _selectedYoloModelKey = 'selected_yolo_model';

  // Ambil base URL dari SharedPreferences
  static Future<String?> getServerUrl() async {
    final prefs = await SharedPreferences.getInstance();
    return prefs.getString(_serverUrlKey);
  }

  // Simpan URL setelah berhasil connect
  static Future<void> setServerUrl(String url) async {
    final prefs = await SharedPreferences.getInstance();
    final cleaned = normalizeServerUrl(url);
    await prefs.setString(_serverUrlKey, cleaned);
  }

  static String normalizeServerUrl(String url) {
    var cleaned = url.trim();
    if (!cleaned.startsWith('http://') && !cleaned.startsWith('https://')) {
      cleaned = 'http://$cleaned';
    }
    while (cleaned.endsWith('/')) {
      cleaned = cleaned.substring(0, cleaned.length - 1);
    }
    return cleaned;
  }

  static Future<void> clearServerUrl() async {
    final prefs = await SharedPreferences.getInstance();
    await prefs.remove(_serverUrlKey);
  }

  static String buildApiUrl(String baseUrl) => '$baseUrl/api/v1';
  static String buildWsUrl(String baseUrl) =>
      '${baseUrl.replaceFirst('http', 'ws')}/ws';

  // Timeouts
  static const Duration connectTimeout = Duration(seconds: 10);
  static const Duration receiveTimeout = Duration(seconds: 30);
  static const Duration pingTimeout = Duration(seconds: 5);

  // Location intervals
  static const int locationIntervalWalkMs = 5000;
  static const int locationIntervalIdleMs = 30000;

  // YOLO
  static const String yoloModelPath = 'assets/models/yolov8n.tflite';
  static const String yoloLabelsPath = 'assets/models/labels.txt';
  static const int yoloInputSize = 640;

  static Future<String> getSelectedYoloModelPath() async {
    final prefs = await SharedPreferences.getInstance();
    return prefs.getString(_selectedYoloModelKey) ?? yoloModelPath;
  }

  static Future<void> setSelectedYoloModelPath(String path) async {
    final prefs = await SharedPreferences.getInstance();
    await prefs.setString(_selectedYoloModelKey, path);
  }

  // Agora - ganti dengan App ID dari agora.io
  static const String agoraAppId = 'YOUR_AGORA_APP_ID';
}
