// test/tool/generate_brand_assets_test.dart
import 'dart:io';
import 'dart:ui';

import 'package:block_seasons/ui/branding/app_icon_painter.dart';
import 'package:block_seasons/ui/branding/feature_graphic_painter.dart';
import 'package:flutter/services.dart';
import 'package:flutter_test/flutter_test.dart';

Future<void> _writePng(String path, int size, void Function(Canvas) draw) async {
  final recorder = PictureRecorder();
  final canvas = Canvas(recorder);
  draw(canvas);
  final picture = recorder.endRecording();
  final image = await picture.toImage(size, size);
  final bytes = await image.toByteData(format: ImageByteFormat.png);
  File(path).parent.createSync(recursive: true);
  File(path).writeAsBytesSync(bytes!.buffer.asUint8List());
}

void main() {
  testWidgets('generate launcher icon PNGs', (tester) async {
    const s = 1024;
    final full = Rect.fromLTWH(0, 0, s.toDouble(), s.toDouble());

    await tester.runAsync(() async {
      // Master (iOS + fallback): opaque navy + blocks at 60%.
      await _writePng('assets/icon/icon.png', s, (c) {
        AppIconMark.paintBackground(c, full);
        AppIconMark.paintBlocks(c, s.toDouble(), groupFraction: 0.6);
      });
      // Adaptive background: navy only.
      await _writePng('assets/icon/icon_background.png', s, (c) {
        AppIconMark.paintBackground(c, full);
      });
      // Adaptive foreground: blocks only (transparent), 52% for the safe zone.
      await _writePng('assets/icon/icon_foreground.png', s, (c) {
        AppIconMark.paintBlocks(c, s.toDouble(), groupFraction: 0.52);
      });
    });

    for (final f in ['icon.png', 'icon_background.png', 'icon_foreground.png']) {
      expect(File('assets/icon/$f').existsSync(), isTrue, reason: f);
    }
  });

  testWidgets('generate feature graphic', (tester) async {
    await tester.runAsync(() async {
      // Load the real display font (OFL Titan One) so the wordmark renders as
      // glyphs — the flutter_test default font draws every char as a box.
      final fontBytes =
          File('tool/fonts/TitanOne-Regular.ttf').readAsBytesSync();
      final loader = FontLoader('TitanOne')
        ..addFont(Future.value(ByteData.view(fontBytes.buffer)));
      await loader.load();

      const w = 1024, h = 500;
      final recorder = PictureRecorder();
      final canvas = Canvas(recorder);
      FeatureGraphic.paint(canvas, const Size(1024, 500));
      final picture = recorder.endRecording();
      final image = await picture.toImage(w, h);
      final bytes = await image.toByteData(format: ImageByteFormat.png);
      File('docs/store/feature_graphic.png').parent.createSync(recursive: true);
      File('docs/store/feature_graphic.png')
          .writeAsBytesSync(bytes!.buffer.asUint8List());
    });
    expect(File('docs/store/feature_graphic.png').existsSync(), isTrue);
  });
}
