import 'dart:convert';
import 'package:http/http.dart' as http;
import 'package:latlong2/latlong.dart';
import '../core/localization/app_localizations.dart';
import '../core/text/wp_text.dart';
import '../models/pedestrian_route.dart';
import '../models/transport_mode.dart';
/// Pedestrian routing abstraction.
///
/// Prototype backend: OpenStreetMap Deutschland's public OSRM foot demo.
/// For production, replace [baseUrl] with a contracted/self-hosted endpoint
/// without changing the UI layer.
class RoutingService {
const RoutingService({
this.baseUrl = 'https://routing.openstreetmap.de/routed-foot',
});
final String baseUrl;
Future<PedestrianRoute> pedestrianRoute(
List<LatLng> waypoints, {
String languageCode = 'de',
}) =>
route(
waypoints,
mode: TransportMode.walking,
languageCode: languageCode,
);
Future<PedestrianRoute> route(
List<LatLng> waypoints, {
required TransportMode mode,
String languageCode = 'de',
}) async {
if (mode == TransportMode.publicTransit) {
throw RoutingException(
AppLocalizations.tFor(languageCode, 'transitRoutingPending'),
);
}
if (waypoints.length < 2) {
throw ArgumentError('At least two waypoints are required.');
}
final coordinates =
waypoints.map((p) => '${p.longitude},${p.latitude}').join(';');
// The routed-foot server is preconfigured with the foot profile. Its
// OSRM API still exposes the historical /driving/ profile path segment.
final endpoint = switch (mode) {
TransportMode.walking => baseUrl,
TransportMode.bicycle => 'https://routing.openstreetmap.de/routed-bike',
TransportMode.carMotorcycle =>
'https://routing.openstreetmap.de/routed-car',
TransportMode.publicTransit => baseUrl,
};
final uri = Uri.parse(
'$endpoint/route/v1/driving/$coordinates'
'?overview=full&geometries=geojson&steps=true&alternatives=false',
);
final response = await http.get(
uri,
headers: const {
'Accept': 'application/json',
},
).timeout(const Duration(seconds: 12));
if (response.statusCode != 200) {
throw RoutingException('Routing HTTP ${response.statusCode}');
}
final root = jsonDecode(response.body) as Map<String, dynamic>;
if (root['code'] != 'Ok') {
throw RoutingException('Routing returned ${root['code']}');
}
final routes = root['routes'] as List<dynamic>?;
if (routes == null || routes.isEmpty) {
throw const RoutingException('No pedestrian route found.');
}
final route = routes.first as Map<String, dynamic>;
final geometryJson = route['geometry'] as Map<String, dynamic>?;
final rawCoords =
geometryJson?['coordinates'] as List<dynamic>? ?? const [];
final geometry = rawCoords.map((raw) {
final pair = raw as List<dynamic>;
return LatLng(
(pair[1] as num).toDouble(),
(pair[0] as num).toDouble(),
);
}).toList(growable: false);
final steps = <NavigationStep>[];
for (final rawLeg in (route['legs'] as List<dynamic>? ?? const [])) {
final leg = rawLeg as Map<String, dynamic>;
for (final rawStep in (leg['steps'] as List<dynamic>? ?? const [])) {
final step = rawStep as Map<String, dynamic>;
final maneuver = step['maneuver'] as Map<String, dynamic>? ?? const {};
final name = WpText.nullablePlain(step['name']);
steps.add(
NavigationStep(
instruction: _instructionFor(
type: maneuver['type'] as String?,
modifier: maneuver['modifier'] as String?,
streetName: name,
languageCode: languageCode,
),
maneuverType: maneuver['type'] as String?,
maneuverModifier: maneuver['modifier'] as String?,
streetName: name?.isEmpty == true ? null : name,
distanceMeters: (step['distance'] as num? ?? 0).toDouble(),
durationSeconds: (step['duration'] as num? ?? 0).toDouble(),
),
);
}
}
if (geometry.length < 2) {
throw const RoutingException('Route geometry is empty.');
}
return PedestrianRoute(
geometry: geometry,
distanceMeters: (route['distance'] as num? ?? 0).toDouble(),
durationSeconds: (route['duration'] as num? ?? 0).toDouble(),
steps: steps,
);
}
String _instructionFor({
required String? type,
required String? modifier,
required String? streetName,
required String languageCode,
}) {
final street = streetName == null || streetName.isEmpty
? ''
: AppLocalizations.tfFor(
languageCode,
'onStreet',
{'street': streetName},
);
String text(String key) => AppLocalizations.tFor(languageCode, key);
switch (type) {
case 'depart':
return AppLocalizations.tfFor(
languageCode,
'routeDepart',
{'street': street},
);
case 'arrive':
return text('routeArrive');
case 'roundabout':
case 'rotary':
return AppLocalizations.tfFor(
languageCode,
'routeRoundabout',
{'street': street},
);
case 'continue':
case 'new name':
return AppLocalizations.tfFor(
languageCode,
'routeStraight',
{'street': street},
);
case 'turn':
case 'end of road':
case 'fork':
return '${_turnText(modifier, languageCode)}$street';
default:
if (modifier != null) {
return '${_turnText(modifier, languageCode)}$street';
}
return street.isEmpty
? text('routeFollow')
: AppLocalizations.tfFor(
languageCode,
'routeContinue',
{'street': street},
);
}
}
String _turnText(String? modifier, String languageCode) {
final key = switch (modifier) {
'left' => 'turnLeft',
'slight left' => 'turnSlightLeft',
'sharp left' => 'turnSharpLeft',
'right' => 'turnRight',
'slight right' => 'turnSlightRight',
'sharp right' => 'turnSharpRight',
'uturn' => 'turnUTurn',
'straight' => 'routeStraight',
_ => 'routeFollow',
};
return AppLocalizations.tFor(languageCode, key);
}
}
class RoutingException implements Exception {
const RoutingException(this.message);
final String message;
@override
String toString() => message;
}

