import 'package:flutter/material.dart';
import 'package:sentry_flutter/sentry_flutter.dart';
import 'sentry_service.dart';

/// Sentry 导航观察器
/// 自动追踪页面导航，记录面包屑和性能指标
class SentryNavigationObserver extends NavigatorObserver {
  final bool enablePerformanceTracing;

  SentryNavigationObserver({
    this.enablePerformanceTracing = true,
  });

  @override
  void didPush(Route<dynamic> route, Route<dynamic>? previousRoute) {
    super.didPush(route, previousRoute);
    _recordNavigation(
      from: _extractRouteName(previousRoute),
      to: _extractRouteName(route),
      action: 'push',
    );
  }

  @override
  void didPop(Route<dynamic> route, Route<dynamic>? previousRoute) {
    super.didPop(route, previousRoute);
    _recordNavigation(
      from: _extractRouteName(route),
      to: _extractRouteName(previousRoute),
      action: 'pop',
    );
  }

  @override
  void didReplace({Route<dynamic>? newRoute, Route<dynamic>? oldRoute}) {
    super.didReplace(newRoute: newRoute, oldRoute: oldRoute);
    _recordNavigation(
      from: _extractRouteName(oldRoute),
      to: _extractRouteName(newRoute),
      action: 'replace',
    );
  }

  @override
  void didRemove(Route<dynamic> route, Route<dynamic>? previousRoute) {
    super.didRemove(route, previousRoute);
    _recordNavigation(
      from: _extractRouteName(route),
      to: _extractRouteName(previousRoute),
      action: 'remove',
    );
  }

  void _recordNavigation({
    required String? from,
    required String? to,
    required String action,
  }) {
    final fromName = from ?? 'unknown';
    final toName = to ?? 'unknown';

    // 记录面包屑
    SentryService().addNavigationBreadcrumb(
      from: fromName,
      to: toName,
    );

    // 使用 Sentry 内置的导航追踪
    if (enablePerformanceTracing && SentryService().isInitialized) {
      Sentry.configureScope((scope) {
        scope.setContexts('navigation', {
          'from': fromName,
          'to': toName,
          'action': action,
          'timestamp': DateTime.now().toIso8601String(),
        });
      });
    }
  }

  String? _extractRouteName(Route<dynamic>? route) {
    if (route == null) return null;

    // 优先使用路由设置中的名称
    if (route.settings.name != null && route.settings.name!.isNotEmpty) {
      return route.settings.name;
    }

    // 尝试从路由类型推断
    final routeType = route.runtimeType.toString();
    if (routeType.contains('MaterialPageRoute') ||
        routeType.contains('CupertinoPageRoute')) {
      return route.settings.name ?? 'unnamed_route';
    }

    return routeType;
  }
}

/// Sentry 内置导航观察器的扩展包装
/// 结合自定义逻辑和 Sentry 原生功能
class CombinedSentryNavigationObserver extends SentryNavigatorObserver {
  final SentryNavigationObserver _customObserver;

  CombinedSentryNavigationObserver({
    bool enablePerformanceTracing = true,
  })  : _customObserver = SentryNavigationObserver(
          enablePerformanceTracing: enablePerformanceTracing,
        ),
        super(
          enableAutoTransactions: enablePerformanceTracing,
        );

  @override
  void didPush(Route<dynamic> route, Route<dynamic>? previousRoute) {
    super.didPush(route, previousRoute);
    _customObserver.didPush(route, previousRoute);
  }

  @override
  void didPop(Route<dynamic> route, Route<dynamic>? previousRoute) {
    super.didPop(route, previousRoute);
    _customObserver.didPop(route, previousRoute);
  }

  @override
  void didReplace({Route<dynamic>? newRoute, Route<dynamic>? oldRoute}) {
    super.didReplace(newRoute: newRoute, oldRoute: oldRoute);
    _customObserver.didReplace(newRoute: newRoute, oldRoute: oldRoute);
  }

  @override
  void didRemove(Route<dynamic> route, Route<dynamic>? previousRoute) {
    super.didRemove(route, previousRoute);
    _customObserver.didRemove(route, previousRoute);
  }
}
