import 'dart:developer';

import 'package:dio/dio.dart';
import 'package:fuzzywuzzy/fuzzywuzzy.dart';
import 'dart:convert';

import 'package:fuzzywuzzy/model/extracted_result.dart';

const String baseUrl = "https://en.wikipedia.org/w/api.php";
final Dio dio = Dio();

Future<int?> bestPageMatch(String title) async {
    final response = await dio.get(baseUrl, queryParameters: {
        "action": "query",
        "format": "json",
        "list": "prefixsearch",
        "pssearch": title,
    });

    final data = jsonDecode(response.toString());
    log(data.toString());
    final List<dynamic> results = data["query"]["prefixsearch"] ?? {};
    final Map<String, int> titlesAndIds = {
        for (var d in results) d["title"]: d["pageid"]
    };
    if (titlesAndIds.isEmpty) {
        log("No pages found for $title");
        return null;
    }

    // after the empty check, we can safely assume that there is a best match
    final ExtractedResult<String> bestMatch = extractOne(
      query: title,
      choices: titlesAndIds.keys.toList(),
      cutoff: 70,
    );
    return titlesAndIds[bestMatch.choice];
}

Future<String?> getImageUrl(int pageId) async {
    final response = await dio.get(baseUrl, queryParameters: {
        "action": "query",
        "format": "json",
        "prop": "pageimages",
        "pageids": pageId,
        "pithumbsize": 500,
    });

    final data = jsonDecode(response.toString());
    final pageData = data["query"]["pages"][pageId.toString()];
    return pageData["thumbnail"]?["source"];
}

Future<String?> getImageUrlFromName(String title) async {
    int? pageId = await bestPageMatch(title);
    if (pageId == null) {
        return null;
    }
    return await getImageUrl(pageId);
}


Future<String?> getImageUrlFromGooglePhotos(String url) async {
    // this is a very simple implementation that just gets the image behind the link
    // it is not guaranteed to work for all google photos links
    final response = await dio.get(url);
    final data = response.toString();
    final int start = data.indexOf("https://lh3.googleusercontent.com");
    final int end = data.indexOf('"', start);
    return data.substring(start, end);
}
