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'},
      );
    }

    if (!RegExp(r'(go+|ga+)(\s+(go+|ga+))').hasMatch(inputText)) {
      return Response.json(
        statusCode: HttpStatus.badRequest,
        body: {'error': 'text must be baby talk for proper translation, e.g. "googoo"', "input": inputText},
      );
    }

    final String selectedTranslation = selectSimilarLengthTranslation(inputText);

    final id = const Uuid().v4();
    final translation = TranslationRequest(
      id: id,
      inputText: inputText,
      timestamp: DateTime.now(),
      result: selectedTranslation,
      userId: userId,
    );

    MemoryStore.addGoogooTranslation(translation);

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

final List<String> translations = [
  'I really need my Enfamil formula right now!',
  'The Pampers diapers you put on me are so comfy and dry.',
  "Could you warm up my Gerber sweet potato puree? I'm getting hungry.",
  'This Graco stroller ride is making me sleepy.',
  "Mom, the Johnson's Baby Shampoo doesn't hurt my eyes at all - thank you!",
  'I love when you feed me Similac Pro-Advance, it makes my tummy feel good.',
  'This UPPAbaby Vista stroller gives me the best view of everything!',
  'The Huggies wipes are so gentle on my sensitive skin.',
  'Can we try the new Beech-Nut organic apple and pear puree today?',
  "My Carter's onesie is so soft and cozy, I could sleep all day in it.",
  'The Chicco car seat makes me feel safe and secure during our drives.',
  "Mom, I'm loving these Earth's Best organic teething biscuits!",
  "Could you get more Plum Organics squeeze pouches? They're my favorite!",
  'This Baby Bjorn carrier lets me snuggle close to you while we walk.',
  'The Honest Company diapers have such cute patterns, and they feel nice too!',
  "I'm ready for my Nestlé Cerelac breakfast, please!",
  'My Fisher-Price mobile helps me fall asleep so peacefully.',
  "The Philips Avent bottle doesn't give me any gas bubbles.",
  "Mom, these Ella's Kitchen fruit purees are better than candy!",
  'My Britax stroller rides are always so smooth and comfortable.',
  "Could you warm up some Kabrita goat milk formula? I'm getting hungry.",
  'The Baby Dove soap makes bathtime so much fun!',
  "I love my Dr. Brown's bottles, they help me drink without getting too much air.",
  'These Happy Baby puffs are perfect for my little fingers to practice grabbing!',
  'My Nuna PIPA car seat is the coziest place to nap during errands.',
  'Mom, the Gerber rice cereal with banana is my absolute favorite breakfast!',
  'This Doona stroller-car seat combo makes transitions so easy for both of us!',
  'The Seventh Generation diapers are so eco-friendly and comfortable!',
  "Could we try the new Parent's Choice organic vegetable blend?",
  'My Cybex stroller rides are always an adventure!',
  'The Babyganics bubble bath makes me feel so clean and happy!',
  'Mom, I really love when you feed me Fresh Bellies veggie purees!',
  'These Mam pacifiers are perfect for soothing me to sleep.',
  'The Bugaboo Fox stroller gives me the smoothest ride in the neighborhood!',
  'Could you get more Little Spoon organic baby food? It tastes just like your cooking!',
  'My Skip Hop play mat is the best place for tummy time!',
  'The Evenflo bottle makes feeding time so comfortable!',
  'Mom, these Sprout organic quinoa puffs are so tasty!',
  'My Silver Cross stroller makes me feel like royalty!',
  'The Bobbie organic formula is just what I need right now!',
  'Milk, please!',
  "I'm sleepy.",
  'Change me now!',
  'My Enfamil, mommy!',
  'This Graco swing rocks!',
  'Snuggle time with my Boppy pillow!',
  'I love my new UPPAbaby stroller adventures!',
  'The Gerber banana puree is calling my name, mom!',
  'Mom, these Honest Company diapers are getting full!',
  "I really need my Similac Pro-Advance formula right this minute, I'm starving!",
  'This Bugaboo stroller ride through the park is making me so happy I could giggle all day!',
  "Mommy, I know the Plum Organics sweet potato and apple puree is in the cabinet - that's what I want!",
  "Mom, I've been trying to tell you all day that my Carter's onesie is a bit itchy, could we try the bamboo one instead?",
  'I absolutely adore when we go on our morning walks in the Nuna MIXX stroller - the fresh air and gentle bounce always make me feel so peaceful and content!',
  "Dear mommy, I know it's 3 AM, but I've been dreaming about that delicious Beech-Nut organic apple and pear puree, and my tummy is telling me it's time for a midnight snack!",
  "Mom, I really appreciate how you always make sure to stock up on Enfamil Gentlease formula, Pampers Swaddlers diapers, and Huggies Natural Care wipes - you're the best mom ever and I love you to the moon and back!",
  "I've been trying to explain all morning that the combination of my new Cybex e-Priam stroller, my cozy Honest Company diapers, and the fresh Ella's Kitchen fruit puree make this the absolute perfect day for a long walk in the park, followed by a picnic and maybe even some tummy time on that new Skip Hop playmat you bought last week!",
  "Mommy, I know you're tired, but I just wanted to let you know that the way you take care of me - from the gentle Baby Dove soap you use at bathtime, to the perfectly warmed Dr. Brown's bottles of Similac Pro-Total Comfort formula, to the soft Burt's Bees baby clothes you dress me in - makes me feel like the luckiest baby in the whole wide world, and even though I can't say it clearly yet, I love you more than anything!",
  'Hungry!',
  'Wet!',
  'Sleepy now.',
  'Want cuddles!',
  'My tummy hurts.',
];

String selectSimilarLengthTranslation(String input, {double tolerance = 0.3}) {
  // Calculate the target length
  final targetLength = input.length;

  // Filter translations that are within the tolerance range
  final similarLengthTranslations = translations.where((t) {
    final lengthDiff = (t.length - targetLength).abs();
    final maxDiff = targetLength * tolerance;
    return lengthDiff <= maxDiff;
  }).toList();

  // If no translations match the criteria, fall back to the full list
  if (similarLengthTranslations.isEmpty) {
    similarLengthTranslations.addAll(translations);
  }

  // Select a random translation from the filtered list
  final random = Random();
  return similarLengthTranslations[random.nextInt(similarLengthTranslations.length)];
}