import 'dart:io';
import 'dart:math';
import 'package:backend/extensions/request_context.dart';
import 'package:backend/store.dart';
import 'package:dart_frog/dart_frog.dart';
import 'package:shared_models/models/translation_request.dart';
import 'package:shared_models/models/translation_response.dart';
import 'package:uuid/uuid.dart';

Future<Response> onRequest(RequestContext context) async {
  if (context.request.method != HttpMethod.post) {
    return Response(statusCode: HttpStatus.methodNotAllowed);
  }

  try {
    final userId = context.userId;

    final body = await context.request.json() as Map<String, dynamic>;
    final inputText = body['text'] as String?;
    if (inputText == null) {
      return Response.json(
        statusCode: HttpStatus.badRequest,
        body: {'error': 'text field is required'},
      );
    }

    final id = const Uuid().v4();

    final translation = TranslationRequest(
      id: id,
      inputText: inputText,
      timestamp: DateTime.now(),
      result: generateBabyTalk(inputText),
      userId: userId, // Replace with actual translation logic
    );

    MemoryStore.addHumanTranslation(translation);

    return Response.json(
      body: TranslationResponse(
        id: id,
        translatedText: translation.result!,
      ).toJson(),
    );
  } catch (e) {
    return Response.json(
      statusCode: HttpStatus.internalServerError,
      body: {'error': e.toString()},
    );
  }
}

String generateBabyTalk(String input) {
  final random = Random(input.hashCode);
  final syllables = ['goo', 'ga', 'bah', 'ma', 'da', 'ba'];
  final sounds = ['ah', 'oh', 'eh'];

  // Roughly calculate how many syllables we want based on input length
  final targetLength = (input.length / 2).round();

  // Add some randomness to the target length (±30%)
  final variance = (targetLength * 0.3).round();
  final finalLength = targetLength + random.nextInt(variance * 2) - variance;

  final List<String> result = [];

  // Sometimes start with a sound
  if (random.nextBool()) {
    result.add(sounds[random.nextInt(sounds.length)]);
  }

  while (result.join(' ').length < input.length) {
    // Randomly decide to repeat the last syllable
    if (result.isNotEmpty && random.nextDouble() < 0.3) {
      result.add(result.last);
      continue;
    }

    // Randomly combine syllables
    if (random.nextDouble() < 0.4) {
      final syl1 = syllables[random.nextInt(syllables.length)];
      final syl2 = syllables[random.nextInt(syllables.length)];
      result.add('$syl1 $syl2');
    } else {
      result.add(syllables[random.nextInt(syllables.length)]);
    }

    // Sometimes add a sound between syllables
    if (random.nextDouble() < 0.2) {
      result.add(sounds[random.nextInt(sounds.length)]);
    }
  }

  return result.join(' ');
}
