import 'dart:convert';
import 'dart:io';
import 'package:flutter/material.dart';

/// Persists and restores window position and size.
class WindowPersistence {
  static File get _configFile {
    final home = Platform.environment['HOME'] ?? '/tmp';
    return File('$home/.config/imajviewer/window.json');
  }

  /// Save window rect synchronously (safe to call before destroy).
  static void saveSync({
    required Offset position,
    required Size size,
  }) {
    final file = _configFile;
    file.parent.createSync(recursive: true);
    file.writeAsStringSync(jsonEncode({
      'x': position.dx.toInt(),
      'y': position.dy.toInt(),
      'width': size.width.toInt(),
      'height': size.height.toInt(),
    }));
  }

  /// Restore saved window rect. Returns null if no saved config.
  static ({Offset position, Size size})? restore() {
    final file = _configFile;
    if (!file.existsSync()) return null;

    try {
      final data = jsonDecode(file.readAsStringSync()) as Map<String, dynamic>;
      final x = (data['x'] as num?)?.toDouble() ?? 0;
      final y = (data['y'] as num?)?.toDouble() ?? 0;
      final w = (data['width'] as num?)?.toDouble() ?? 1280;
      final h = (data['height'] as num?)?.toDouble() ?? 800;

      if (w < 200 || h < 200 || x < -1000 || y < -1000) return null;

      return (
        position: Offset(x, y),
        size: Size(w, h),
      );
    } catch (_) {
      return null;
    }
  }
}
