import 'dart:io';

import 'package:http/http.dart' as http;
import 'package:video_player/video_player.dart';

const int _maxCachedVideoBytes = 25 * 1024 * 1024;
const Duration _cacheLifetime = Duration(days: 7);

/// Downloads a protected video once, then gives Media Foundation a local file.
/// The local copy also lets the same video replay without an internet request.
Future<Map<String, Object>> prepareNewsVideoSource(
  String url,
  Map<String, String> headers,
) async {
  final uri = Uri.parse(url);
  final cacheDirectory = Directory(
    '${Directory.systemTemp.path}${Platform.pathSeparator}rockview_news_video_cache',
  );
  await cacheDirectory.create(recursive: true);
  await _removeOldCachedVideos(cacheDirectory);

  // The server assigns random names to uploaded video files, so the last URL
  // segment gives this cache a stable name without storing credentials.
  final lastSegment = uri.pathSegments.isEmpty
      ? 'news_video_${url.hashCode}.mp4'
      : uri.pathSegments.last;
  final safeName = lastSegment.replaceAll(RegExp(r'[^A-Za-z0-9._-]'), '_');
  final cachedFile = File(
    '${cacheDirectory.path}${Platform.pathSeparator}$safeName',
  );

  if (!await cachedFile.exists() || await cachedFile.length() == 0) {
    await _downloadVideo(uri, headers, cachedFile);
  }

  return {
    'url': cachedFile.path,
    'headers': <String, String>{},
    'temporary': false,
    'requiresTap': false,
    'controller': VideoPlayerController.file(cachedFile),
  };
}

Future<void> _downloadVideo(
  Uri uri,
  Map<String, String> headers,
  File cachedFile,
) async {
  final partialFile = File('${cachedFile.path}.partial');
  final client = http.Client();
  IOSink? output;

  try {
    if (await partialFile.exists()) await partialFile.delete();
    final request = http.Request('GET', uri)..headers.addAll(headers);
    final response = await client.send(request).timeout(
      const Duration(seconds: 45),
    );

    if (response.statusCode < 200 || response.statusCode >= 300) {
      throw Exception('Video request failed (HTTP ${response.statusCode}).');
    }

    final contentType = (response.headers['content-type'] ?? '').toLowerCase();
    if (contentType.contains('text/html') || contentType.contains('application/json')) {
      throw Exception('The video link returned a web page instead of a video file.');
    }
    final contentLength = response.contentLength;
    if (contentLength != null && contentLength > _maxCachedVideoBytes) {
      throw Exception('The video is too large to prepare for playback.');
    }

    output = partialFile.openWrite();
    var totalBytes = 0;
    await for (final chunk in response.stream.timeout(const Duration(seconds: 30))) {
      totalBytes += chunk.length;
      if (totalBytes > _maxCachedVideoBytes) {
        throw Exception('The video is too large to prepare for playback.');
      }
      output.add(chunk);
    }
    await output.flush();
    await output.close();
    output = null;

    if (totalBytes == 0) throw Exception('The server returned an empty video file.');
    if (await cachedFile.exists()) await cachedFile.delete();
    await partialFile.rename(cachedFile.path);
  } catch (_) {
    if (output != null) await output.close();
    if (await partialFile.exists()) await partialFile.delete();
    rethrow;
  } finally {
    client.close();
  }
}

Future<void> _removeOldCachedVideos(Directory directory) async {
  final cutoff = DateTime.now().subtract(_cacheLifetime);
  await for (final entry in directory.list(followLinks: false)) {
    if (entry is! File) continue;
    try {
      final modifiedAt = await entry.lastModified();
      if (modifiedAt.isBefore(cutoff)) await entry.delete();
    } catch (_) {
      // A file may be in use by the player; it can be cleaned up next time.
    }
  }
}

// Cached video files are intentionally retained for seven days.
void releaseNewsVideoSource(String? url) {}
