import 'dart:async';
import 'dart:convert';
import 'dart:math';
import 'dart:typed_data';
import 'package:crypto/crypto.dart';
import 'package:flutter/foundation.dart';
import 'package:hive_flutter/hive_flutter.dart';
import 'package:http/http.dart' as http;
import '../networks/api_client.dart';
import 'database_service.dart';
import 'file_model.dart';
import 'file_open.dart';

class FileApiException implements Exception {
  final int status;
  final String message;
  FileApiException(this.status, this.message);
  @override String toString() => message;
}

/// One account-bound client. Metadata is small; binary chunks are loaded lazily.
/// No file bytes are downloaded by sync(). Immutable versions prevent mixed files.
class FileManagementService extends ChangeNotifier {
  static const chunkSize = 512 * 1024;
  static const maxFileBytes = 25 * 1024 * 1024;
  static const maxLocalBytes = 200 * 1024 * 1024;
  static const offlineLease = Duration(hours: 24);
  static final Set<FileManagementService> _instances = {};
  static Future<void>? _hiveReady;
  final String email;
  final String account;
  final http.Client _http = http.Client();
  late final Box<dynamic> _meta;
  late final LazyBox<dynamic> _bytes;
  bool _closed = false;
  bool _accountLocked = false;
  bool _syncing = false;
  bool _uploading = false;
  bool online = false;
  String status = 'Opening saved files…';
  final Map<int, double> downloadProgress = {};
  final Map<int, Future<Uint8List>> _downloads = {};
  int _failureCount = 0;
  DateTime? _retryAfter;
  FileManagementService._(this.email, this.account);

  static Future<String> _currentEmail() async {
    final dynamic user = await DatabaseService.getLocalUser();
    final value = '${user?.email ?? ''}'.trim().toLowerCase();
    if (value.isEmpty || value == 'null') throw StateError('Sign in to access files.');
    return value;
  }
  static Future<FileManagementService> open() async {
    final email = await _currentEmail();
    final account = sha256.convert(utf8.encode('${ApiClient.baseUrl}|$email')).toString().substring(0, 32);
    _hiveReady ??= Hive.initFlutter();
    await _hiveReady;
    final s = FileManagementService._(email, account);
    s._meta = await Hive.openBox<dynamic>('rvu_files_meta_$account');
    s._bytes = await Hive.openLazyBox<dynamic>('rvu_files_data_$account');
    await s._guard();
    _instances.add(s);
    s.status = s.hasValidLease ? 'Saved files ready · checking for updates' : 'Connect to verify file access';
    return s;
  }
  Future<void> _guard() async {
    if (_closed) throw StateError('File Management is closed.');
    String current;
    try { current = await _currentEmail(); } catch (_) { current = ''; }
    if (current != email) {
      _accountLocked = true; _notify();
      throw StateError('Account changed. Reopen File Management.');
    }
  }
  void _notify() { if (!_closed) notifyListeners(); }
  List<ManagedFile> get files => ((_meta.get('manifest') as Map?)?['files'] as List? ?? [])
    .whereType<Map>().map(ManagedFile.new).toList();
  Map get profile => (_meta.get('manifest') as Map?)?['user'] as Map? ?? {};
  Map get _manifest => _meta.get('manifest') as Map? ?? {};
  bool get canCreateFolder => hasValidLease && _manifest['can_create_folder'] == true;
  bool get canCreatePublicFolder => hasValidLease && _manifest['can_create_public_folder'] == true;
  List<Map<String, dynamic>> get publicFolders => !hasValidLease ? [] :
    (_manifest['folders'] as List? ?? []).whereType<Map>()
      .map((f) => Map<String, dynamic>.from(f)).toList();
  Map<int, int> get fileFolderIds => !hasValidLease ? {} : {
    for (final f in (_manifest['files'] as List? ?? []).whereType<Map>())
      if (f['folder_id'] != null) (f['id'] as num).toInt(): (f['folder_id'] as num).toInt(),
  };
  List<Map<String,dynamic>> get folderInvitations => !hasValidLease ? [] :
    (_manifest['invitations'] as List? ?? []).whereType<Map>()
      .map((i)=>Map<String,dynamic>.from(i)).toList();
  Future<void> createFolder(String name, String description, {bool public=false}) async {
    await _requireLease();
    if (!canCreateFolder) throw StateError('Connect to verify folder creation access.');
    await _request('create_folder',body:{'name':name.trim(),'description':description.trim(),
      'visibility':public?'public':'restricted'});
    await sync();
  }
  Future<Map<String,dynamic>> folderDetails(int id) async =>
    _json(await _request('folder_details',query:{'folder_id':'$id'}));
  Future<List<Map<String,dynamic>>> findFolderCandidates(int id,String query) async {
    final data=_json(await _request('folder_candidates',query:{'folder_id':'$id','q':query}));
    return (data['people'] as List? ?? []).whereType<Map>().map((p)=>Map<String,dynamic>.from(p)).toList();
  }
  Future<void> inviteToFolder(int folderId,int userId) async {
    await _request('invite_folder',body:{'folder_id':folderId,'user_id':userId});
  }
  Future<void> respondToFolderInvitation(int folderId,bool accept) async {
    await _request('respond_folder_invite',body:{'folder_id':folderId,'decision':accept?'accepted':'declined'});
    await sync();
  }
  Future<void> deleteFolder(int folderId) async {
    await _request('delete_folder',body:{'folder_id':folderId});
    await sync();
  }
  List<Map<String, dynamic>> get queue => (_accountLocked || _closed ? <dynamic>[] : _meta.get('queue', defaultValue: []) as List)
    .whereType<Map>().map((e) => Map<String, dynamic>.from(e)).toList();
  Map<String, dynamic>? cached(ManagedFile file) {
    final v = _meta.get('cached:${file.id}');
    return v is Map ? Map<String, dynamic>.from(v) : null;
  }
  bool get hasValidLease {
    if (_accountLocked || _closed) return false;
    final when = DateTime.tryParse('${_meta.get('verified_at', defaultValue: '')}');
    if (when == null) return false;
    final age = DateTime.now().difference(when);
    return !age.isNegative && age < offlineLease;
  }
  bool get isUploading => _uploading;
  Future<http.Response> _request(String op, {Map<String, String> query = const {}, Object? body, bool raw = false, Map<String,String> extra = const {}, Duration timeout = const Duration(seconds: 8)}) async {
    await _guard();
    final headers = Map<String,String>.from(await ApiClient.getHeaders());
    headers.removeWhere((key, value) => key.toLowerCase() == 'content-type');
    headers.addAll(extra);
    if (body != null) headers['Content-Type'] = raw ? 'application/octet-stream' : 'application/json';
    final uri = Uri.parse('${ApiClient.baseUrl}/api/files.php').replace(queryParameters: {'op': op, ...query});
    final response = await (body == null
      ? _http.get(uri, headers: headers)
      : _http.post(uri, headers: headers, body: raw ? body : jsonEncode(body)))
      .timeout(timeout);
    await _guard();
    bool suspended=false;
    if(response.statusCode==403) {
      try { suspended=(jsonDecode(response.body) as Map)['code']=='account_suspended'; } catch (_) {}
    }
    // A 401 can result from Authorization being dropped by shared hosting.
    // Keep account-scoped offline copies; the lease still limits access and a
    // later successful manifest refresh reconciles current permissions.
    // Explicit suspension or a forbidden manifest remains a revocation signal.
    if (suspended || (response.statusCode == 403 && op == 'manifest')) {
      await _meta.clear(); await _bytes.clear(); await clearManagedExports(account);
      _notify();
    }
    await ApiClient.handleUnauthorized(response);
    if (response.statusCode == 404 && query.containsKey('id') && (op=='meta'||op=='download')) {
      await _removeCachedKey('cached:${query['id']}');
    }
    if (response.statusCode >= 400) {
      String message = 'Request failed (${response.statusCode}).';
      try { message = '${(jsonDecode(response.body) as Map)['detail'] ?? message}'; } catch (_) {}
      throw FileApiException(response.statusCode, message);
    }
    return response;
  }
  Map<String,dynamic> _json(http.Response r) => Map<String,dynamic>.from(jsonDecode(r.body) as Map);

  Future<void> sync() async {
    if (_closed || _syncing) return;
    _syncing = true;
    try {
      final etag = '${_meta.get('etag', defaultValue: '')}';
      final r = await _request('manifest', extra: etag.isEmpty ? {} : {'If-None-Match': etag});
      if (r.statusCode != 304) {
        final manifest = _json(r);
        if (manifest['files'] is! List || manifest['user'] is! Map) throw const FormatException('Invalid file list.');
        final ids = (manifest['files'] as List).map((e) => '${e['id']}').toSet();
        // This endpoint is a complete authorised manifest, never a filtered page.
        for (final key in _meta.keys.whereType<String>().where((k) => k.startsWith('cached:')).toList()) {
          if (!ids.contains(key.split(':')[1])) await _removeCachedKey(key);
        }
        for (final key in _bytes.keys.whereType<String>().where((k) => k.startsWith('file:')).toList()) {
          if (!ids.contains(key.split(':')[1])) await _bytes.delete(key);
        }
        await _meta.put('manifest', manifest);
        await _meta.put('etag', r.headers['etag'] ?? '');
      }
      await _meta.put('verified_at', DateTime.now().toIso8601String());
      online = true; status = 'Up to date · saved files open offline';
      _failureCount = 0;
    } catch (e) {
      online = false;
      status = e is FileApiException && e.status == 403
          ? e.message
          : 'Offline · showing saved files';
    } finally { _syncing = false; _notify(); }
  }
  Future<void> _requireLease() async {
    await _guard();
    if (!hasValidLease) await sync();
    if (!hasValidLease) throw StateError('Connect to the internet to renew file access.');
  }
  Future<void> _removeCachedKey(String key) async {
    final entry = _meta.get(key);
    if (entry is Map) {
      final prefix = '${entry['prefix']}';
      for (final k in _bytes.keys.whereType<String>().where((k) => k.startsWith(prefix)).toList()) {
        await _bytes.delete(k);
      }
    }
    await _meta.delete(key);
  }
  Future<void> clearDownloads() async {
    await _guard();
    if (_downloads.isNotEmpty) throw StateError('Wait for the current download to finish.');
    for (final key in _meta.keys.whereType<String>().where((k) => k.startsWith('cached:')).toList()) {
      await _removeCachedKey(key);
    }
    for (final key in _bytes.keys.whereType<String>().where((k) => k.startsWith('file:')).toList()) {
      await _bytes.delete(key);
    }
    await clearManagedExports(account);_notify();
  }
  Future<Uint8List> _readChunks(String prefix, int size) async {
    final out = BytesBuilder(copy: false);
    for (int offset = 0; offset < size; offset += chunkSize) {
      final bytes = await _bytes.get('$prefix$offset');
      if (bytes is! Uint8List || bytes.length != min(chunkSize, size - offset)) {
        throw StateError('Saved file is incomplete. Download it again.');
      }
      out.add(bytes);
    }
    return out.takeBytes();
  }
  Future<Uint8List> savedBytes(ManagedFile file) async {
    await _requireLease();
    if (!files.any((f) => f.id == file.id)) throw StateError('File access was removed.');
    final entry = cached(file);
    if (entry == null) throw StateError('This file has not been saved offline.');
    final bytes = await _readChunks('${entry['prefix']}', (entry['size'] as num).toInt());
    if (sha256.convert(bytes).toString() != entry['sha256']) {
      await _removeCachedKey('cached:${file.id}');_notify();
      throw StateError('Saved copy failed verification. Download it again.');
    }
    return bytes;
  }
  Future<Uint8List> download(ManagedFile file) {
    final existing = _downloads[file.id]; if (existing != null) return existing;
    final future = _download(file);
    _downloads[file.id] = future;
    return future.whenComplete(() { _downloads.remove(file.id); downloadProgress.remove(file.id); _notify(); });
  }
  Future<Uint8List> _download(ManagedFile file) async {
    await _requireLease();
    final local = cached(file);
    if (local != null && local['version'] == file.version && local['sha256'] == file.checksum) {
      return savedBytes(file); // No byte request for an already-downloaded version.
    }
    if (local != null && local['sha256'] == file.checksum && local['size'] == file.size) {
      final bytes = await savedBytes(file);
      await _meta.put('cached:${file.id}', {...local,'version':file.version,'filename':file.filename});
      _notify();return bytes; // A metadata-only replacement has identical content.
    }
    final current = _json(await _request('meta', query: {'id':'${file.id}'}));
    if ((current['file']['current_version'] as num).toInt() != file.version) {
      await sync();throw StateError('A new version is available. Open the refreshed file.');
    }
    await _checkSpace(file.size);
    final prefix = file.blobPrefix;
    for (int offset = 0; offset < file.size; offset += chunkSize) {
      await _guard();
      final length = min(chunkSize, file.size-offset);
      final saved = await _bytes.get('$prefix$offset');
      if (saved is! Uint8List || saved.length != length) {
        final r = await _request('download', query: {'id':'${file.id}','version':'${file.version}','offset':'$offset','length':'$length'});
        if (r.bodyBytes.length != length) throw StateError('Download interrupted. Retry to resume.');
        await _bytes.put('$prefix$offset', r.bodyBytes);
      }
      downloadProgress[file.id]=(offset+length)/file.size;_notify();
    }
    final bytes = await _readChunks(prefix,file.size);
    if (sha256.convert(bytes).toString() != file.checksum) {
      for (final key in _bytes.keys.whereType<String>().where((k)=>k.startsWith(prefix)).toList()) { await _bytes.delete(key); }
      throw StateError('Checksum failed. Retry the download.');
    }
    // Only commit a verified complete version. The previous copy survives failures.
    await _meta.put('cached:${file.id}', {'prefix':prefix,'version':file.version,'filename':file.filename,'size':file.size,'sha256':file.checksum});
    if (local != null && local['prefix'] != prefix) {
      for(final key in _bytes.keys.whereType<String>().where((k)=>k.startsWith('${local['prefix']}')).toList()) { await _bytes.delete(key); }
    }
    _notify(); return bytes;
  }
  Future<void> _checkSpace(int additional) async {
    int used=0;
    // Lazy box does not load all files into memory; only one chunk at a time.
    for(final key in _bytes.keys.toList()) {
      final v=await _bytes.get(key);if(v is Uint8List) used+=v.length;
    }
    if(used+additional>maxLocalBytes) throw StateError('Offline storage is full. Clear saved downloads before adding more.');
  }
  Future<void> openFile(ManagedFile file, {bool savedOnly=false}) async {
    final bytes = savedOnly ? await savedBytes(file) : await download(file);
    await _guard();
    final local = cached(file);
    final name = savedOnly && local != null
        ? (local['filename'] ?? file.filename).toString()
        : file.filename;
    final version = savedOnly && local != null
        ? (local['version'] ?? file.version)
        : file.version;
    await openManagedBytes(bytes, '${file.id}_${version}_$name', account);
  }
  Future<void> queueUpload(String name, String title, Uint8List bytes, {ManagedFile? replacing, int? folderId}) async {
    await _requireLease();
    folderId = replacing == null ? folderId : fileFolderIds[replacing.id];
    if (folderId != null && !publicFolders.any((f) => f['id'] == folderId && f['can_upload'] == true)) {
      throw StateError('Choose a folder you own.');
    }
    if(bytes.isEmpty||bytes.length>maxFileBytes) throw StateError('Choose a file between 1 byte and 25 MB.');
    if(queue.length>=5) throw StateError('Finish or remove a queued upload before adding more.');
    await _checkSpace(bytes.length);
    final id=List.generate(16,(_)=>Random.secure().nextInt(256).toRadixString(16).padLeft(2,'0')).join();
    for(int offset=0;offset<bytes.length;offset+=chunkSize) {
      await _bytes.put('upload:$id:$offset',Uint8List.fromList(bytes.sublist(offset,min(offset+chunkSize,bytes.length))));
    }
    final q=queue;
    q.add({'key':id,'filename':name,'title':title,'size_bytes':bytes.length,'sha256':sha256.convert(bytes).toString(),
      'folder_id':folderId,'file_id':replacing?.id??0,'expected_version':replacing?.version??0,'state':'Pending','offset':0});
    await _meta.put('queue',q);_notify();
    await drainQueue();
  }
  Future<void> _saveJob(Map<String,dynamic> job) async {
    await _guard();final q=queue;final i=q.indexWhere((e)=>e['key']==job['key']);
    if(i>=0){q[i]=job;await _meta.put('queue',q);}_notify();
  }
  Future<void> removeJob(String key) async {
    if(_uploading) throw StateError('Wait until the current transfer pauses or finishes.');
    await _removeJob(key);
  }
  Future<void> _removeJob(String key) async {
    final q=queue..removeWhere((e)=>e['key']==key);await _meta.put('queue',q);
    for(final k in _bytes.keys.whereType<String>().where((k)=>k.startsWith('upload:$key:')).toList()) { await _bytes.delete(k); }
    _notify();
  }
  Future<void> retryJob(String key) async {
    if(_uploading)return;
    final job=queue.firstWhere((e)=>e['key']==key);job['state']='Pending';job.remove('error');await _saveJob(job);
    _retryAfter=null;await drainQueue();
  }
  Future<void> drainQueue() async {
    if(_closed||_uploading||(_retryAfter!=null&&DateTime.now().isBefore(_retryAfter!)))return;
    _uploading=true;_notify();
    try {
      await _requireLease();
      for(final job in queue) {
        if(job['state']=='Needs attention')continue;
        try {
          job['state']='Uploading';job.remove('error');await _saveJob(job);
          final begin=_json(await _request('begin',body:{...job,'client_key':job['key']}));
          Map<String,dynamic> completed = {'file_id':begin['result_file_id'],'version':begin['result_version']};
          if(begin['result_file_id']==null) {
            int offset=(begin['offset'] as num).toInt();final total=(job['size_bytes'] as num).toInt();
            while(offset<total) {
              final bytes=await _bytes.get('upload:${job['key']}:$offset');
              if(bytes is! Uint8List)throw StateError('Queued file data is missing. Select the file again.');
              final r=_json(await _request('chunk',query:{'upload_id':'${begin['upload_id']}','offset':'$offset'},body:bytes,raw:true,timeout:const Duration(seconds:30)));
              final next=(r['offset'] as num).toInt();if(next<=offset||next>total)throw StateError('Invalid server upload offset.');
              offset=next;job['offset']=offset;await _saveJob(job);
            }
            completed = _json(await _request('finish',body:{'upload_id':begin['upload_id']}));
          }
          // The original upload bytes are already on this device; reuse them.
          final id = int.parse('${completed['file_id']}');
          final version = int.parse('${completed['version']}');
          final prefix = 'file:$id:$version:';
          for (int offset=0; offset<(job['size_bytes'] as num); offset+=chunkSize) {
            final chunk = await _bytes.get('upload:${job['key']}:$offset');
            if (chunk is! Uint8List) throw StateError('Queued file data is missing.');
            await _bytes.put('$prefix$offset', chunk);
          }
          final previous = _meta.get('cached:$id');
          await _meta.put('cached:$id', {'prefix':prefix,'version':version,'filename':job['filename'],'size':job['size_bytes'],'sha256':job['sha256']});
          if(previous is Map && previous['prefix'] != prefix) {
            for(final k in _bytes.keys.whereType<String>().where((k)=>k.startsWith('${previous['prefix']}')).toList()) { await _bytes.delete(k); }
          }
          await _removeJob('${job['key']}');_failureCount=0;_retryAfter=null;await sync();
        } catch(e) {
          if(_closed)break;
          final permanent=e is FileApiException && e.status>=400 && e.status<500 && e.status!=408 && e.status!=429;
          job['state']=permanent||e is StateError?'Needs attention':'Waiting for connection';job['error']=e.toString();await _saveJob(job);
          _failureCount=min(_failureCount+1,6);_retryAfter=DateTime.now().add(Duration(seconds: min(300,5*(1<<_failureCount))));
          break;
        }
      }
    } catch(e) {status=e.toString();} finally {_uploading=false;_notify();}
  }
  Future<void> deleteFile(ManagedFile file) async {
    await _request('delete',body:{'id':file.id,'expected_version':file.version});await sync();
  }
  /// Call before clearing the login session on sign-out/account switch.
  static Future<void> clearForLogout() async {
    final email=await _currentEmail();
    final account=sha256.convert(utf8.encode('${ApiClient.baseUrl}|$email')).toString().substring(0,32);
    for(final s in _instances.toList()) { if(s.account==account)s.dispose(); }
    _hiveReady??=Hive.initFlutter();await _hiveReady;
    final m=await Hive.openBox<dynamic>('rvu_files_meta_$account');
    final b=await Hive.openLazyBox<dynamic>('rvu_files_data_$account');
    await m.clear();await b.clear();await clearManagedExports(account);
  }
  @override void dispose() {
    if(_closed)return;_closed=true;_http.close();_instances.remove(this);super.dispose();
  }
}
