class RtmpStreamTarget {
  const RtmpStreamTarget({required this.url, required this.streamKey});

  final String url;
  final String streamKey;

  factory RtmpStreamTarget.parse(String value) {
    final source = value.trim();
    final uri = Uri.tryParse(source);
    if (uri == null ||
        (uri.scheme != 'rtmp' && uri.scheme != 'rtmps') ||
        uri.host.isEmpty) {
      throw const FormatException('推流地址必须是 rtmp:// 或 rtmps:// 开头的完整地址');
    }

    final pathSegments = uri.pathSegments
        .where((segment) => segment.trim().isNotEmpty)
        .toList(growable: false);
    if (pathSegments.length < 2) {
      throw const FormatException('推流地址路径必须包含 app 和 streamKey，例如 /app/xxxx');
    }

    final appPath = pathSegments.take(pathSegments.length - 1).join('/');
    final streamKey = pathSegments.last;
    final baseUrl = uri
        .replace(path: '/$appPath', query: null, fragment: null)
        .toString();

    return RtmpStreamTarget(url: baseUrl, streamKey: streamKey);
  }

  String get fullUrl => '$url/$streamKey';
}
