import 'dart:developer' as dev;
import '../services/database_service.dart';
import '../logic/capacity_extractor.dart';
import '../models/saf_permission_state.dart';
import '../services/saf_storage_service.dart';

/// 电池数据服务：扫描日志、更新数据库
class BatteryDataService {
  final SafStorageService _safService = SafStorageService();
  final DatabaseService _dbService = DatabaseService();

  /// 扫描所有日志文件并更新数据库
  Future<void> scanAndUpdateDB() async {
    dev.log('🔵 scanAndUpdateDB 开始', name: 'BatteryHealth');

    final state = await _safService.getPermissionState();
    if (state != SafPermissionState.authorized) {
      dev.log('🔵 scanAndUpdateDB: 未授权', name: 'BatteryHealth');
      return;
    }

    try {
      final files = await _safService.listFiles();
      final filePattern = RegExp(r'mbattery_charger_log_(\d{4}_\d{2}_\d{2})$');

      for (String fileName in files) {
        final match = filePattern.firstMatch(fileName);
        if (match == null) continue;

        final dateStr = match.group(1)!.replaceAll('_', '-');
        dev.log('🔵 处理文件: $fileName, 日期: $dateStr', name: 'BatteryHealth');

        try {
          final lines = await _safService.readLogFile(fileName);
          if (lines.isEmpty) continue;

          // 🟢 1.4.5 改进：使用 CapacityExtractor 提取容量（仅从 Full 状态提取）
          int? cap = CapacityExtractor.extractCapacity(lines);

          // 🟢 如果今天没有充满电（cap == null），尝试从昨天复制数据
          if (cap == null) {
            dev.log('🔵 日期 $dateStr 无充满记录，尝试复制前一天数据', name: 'BatteryHealth');

            // 查询最近一条已有数据
            final recentData = await _dbService.queryRecentData(1);
            if (recentData.isNotEmpty) {
              final yesterdayCap = recentData.first['capacity'] as int;
              final yesterdayMaxVolt =
                  recentData.first['volt_max'] as double? ?? 0.0;
              final yesterdayMinVolt =
                  recentData.first['volt_min'] as double? ?? 0.0;

              dev.log(
                '🔵 复制前一天数据: cap=$yesterdayCap, date=$dateStr',
                name: 'BatteryHealth',
              );

              // 🟢 复制昨天的容量和电压极值到今天
              await _dbService.insertOrUpdate(
                dateStr,
                yesterdayCap,
                yesterdayMaxVolt,
                yesterdayMinVolt,
              );
            } else {
              dev.log('🔵 无历史数据可复制，跳过日期 $dateStr', name: 'BatteryHealth');
            }
            continue; // 已处理，跳过后续电压提取逻辑
          }

          // 提取电压极值（从所有有效行提取，不限于 Full）
          final voltReg = RegExp(r'vbat=(\d+)');
          double? maxVolt, minVolt;
          for (String line in lines) {
            if (!line.contains('tbat=')) continue;
            final match = voltReg.firstMatch(line);
            if (match != null) {
              final v = int.parse(match.group(1)!) / 1000000;
              if (maxVolt == null || v > maxVolt) maxVolt = v;
              if (minVolt == null || v < minVolt) minVolt = v;
            }
          }
          if (maxVolt == null || minVolt == null) continue;

          await _dbService.insertOrUpdate(dateStr, cap, maxVolt, minVolt);
          dev.log('🔵 插入数据库: $dateStr, cap=$cap', name: 'BatteryHealth');
        } catch (e) {
          dev.log('🔵 处理文件 $fileName 异常: $e', name: 'BatteryHealth');
        }
      }
    } catch (e) {
      dev.log('🔵 scanAndUpdateDB 异常: $e', name: 'BatteryHealth');
    }
  }

  /// 获取趋势数据（最近 N 天）
  Future<List<Map<String, dynamic>>> getTrendData(int days) async {
    return await _dbService.queryRecentData(days);
  }

  /// 获取最近一条数据
  Future<Map<String, dynamic>?> getLatestData() async {
    final data = await _dbService.queryRecentData(1);
    if (data.isNotEmpty) return data.first;
    return null;
  }
}
