#include "aoc.hpp"

#include <algorithm>
#include <chrono>
#include <exception>
#include <iomanip>
#include <iostream>
#include <iterator>
#include <locale>
#include <sstream>
#include <string>
#include <string_view>
#include <utility>

#ifdef __EMSCRIPTEN__
#include <emscripten/html5.h>
#endif

#ifndef __EMSCRIPTEN__
#include <fstream>
#endif

namespace aoc {

namespace {

double now_ms() {
#ifdef __EMSCRIPTEN__
  return emscripten_performance_now();
#else
  return std::chrono::duration<double, std::milli>(
      std::chrono::steady_clock::now().time_since_epoch()).count();
#endif
}

}  // namespace

Input split_lines(std::string_view input) {
  std::istringstream stream{std::string(input)};
  Input lines;
  std::string line;
  while (std::getline(stream, line)) {
    if (!line.empty() && line.back() == '\r') line.pop_back();
    lines.push_back(line);
  }
  return lines;
}

TimedAnswer time_solve(Solve solve, const Input& input) {
  const double start = now_ms();
  auto answer = solve(input);
  const double end = now_ms();
  double ms = end - start;
  unsigned runs = 1;

#ifdef __EMSCRIPTEN__
  // A single fast call can fall entirely within one browser clock tick.
  constexpr double target_ms = 50.0;
  constexpr unsigned max_runs = 1u << 20;
  if (ms < target_ms) {
    const double benchmark_start = now_ms();
    double benchmark_end = benchmark_start;
    unsigned batch = 1;
    runs = 0;
    while (runs < max_runs && benchmark_end - benchmark_start < target_ms) {
      const unsigned count = std::min(batch, max_runs - runs);
      for (unsigned i = 0; i < count; ++i) {
        solve(input);
      }
      runs += count;
      benchmark_end = now_ms();
      batch = std::min(batch * 2, max_runs);
    }
    ms = (benchmark_end - benchmark_start) / runs;
  }
#endif

  return {std::move(answer), ms, runs};
}

}  // namespace aoc

#ifdef __EMSCRIPTEN__
namespace {

std::string json_string(std::string_view value) {
  constexpr char hex[] = "0123456789abcdef";
  std::string encoded = "\"";
  for (unsigned char ch : value) {
    switch (ch) {
      case '"': encoded += "\\\""; break;
      case '\\': encoded += "\\\\"; break;
      case '\b': encoded += "\\b"; break;
      case '\f': encoded += "\\f"; break;
      case '\n': encoded += "\\n"; break;
      case '\r': encoded += "\\r"; break;
      case '\t': encoded += "\\t"; break;
      default:
        if (ch < 0x20) {
          encoded += "\\u00";
          encoded += hex[ch >> 4];
          encoded += hex[ch & 0x0f];
        } else {
          encoded += static_cast<char>(ch);
        }
    }
  }
  encoded += '"';
  return encoded;
}

std::string json_number(double value) {
  std::ostringstream formatted;
  formatted.imbue(std::locale::classic());
  formatted << std::setprecision(12) << value;
  return formatted.str();
}

}  // namespace

extern "C" const char* aoc_run(const char* day, const char* input) {
  static std::string response;
  try {
    aoc::Result result;
    if (!aoc::solve_day(day ? day : "", aoc::split_lines(input ? input : ""), result)) {
      response = R"({"error":"Unknown day. Rebuild the site after adding a solution."})";
    } else {
      response = "{\"part1\":" + json_string(result.part1) +
                 ",\"part2\":" + json_string(result.part2) +
                 ",\"part1Ms\":" + json_number(result.part1_ms) +
                 ",\"part2Ms\":" + json_number(result.part2_ms) +
                 ",\"part1Runs\":" + std::to_string(result.part1_runs) +
                 ",\"part2Runs\":" + std::to_string(result.part2_runs) +
                 ",\"variants\":[";
      bool first_variant = true;
      for (const auto& variant : result.variants) {
        if (!first_variant) response += ',';
        first_variant = false;
        response += "{\"part\":" + std::to_string(variant.part) +
                    ",\"name\":" + json_string(variant.name) +
                    ",\"answer\":" + json_string(variant.answer) +
                    ",\"ms\":" + json_number(variant.ms) +
                    ",\"runs\":" + std::to_string(variant.runs) + "}";
      }
      response += "]}";
    }
  } catch (const std::exception& error) {
    response = "{\"error\":" + json_string(error.what()) + "}";
  } catch (...) {
    response = R"({"error":"The C++ solution failed."})";
  }
  return response.c_str();
}

#else

namespace {

std::string format_ms(double elapsed) {
  if (elapsed > 0 && elapsed < 0.001) return "<0.001 ms";
  std::ostringstream formatted;
  formatted << std::fixed << std::setprecision(3) << elapsed << " ms";
  return formatted.str();
}

void print_variants(const aoc::Result& result, int part) {
  for (const auto& variant : result.variants) {
    if (variant.part != part) continue;
    std::cout << variant.name << " (" << format_ms(variant.ms) << "):\n"
              << variant.answer << '\n';
  }
}

}  // namespace

int main(int argc, char* argv[]) {
  if (argc < 2 || argc > 3) {
    std::cerr << "Usage: aoc2026 dayNN [input.txt]\nAvailable: "
              << aoc::available_days() << '\n';
    return 2;
  }

  std::ifstream file;
  std::istream* input_stream = &std::cin;
  if (argc == 3) {
    file.open(argv[2], std::ios::binary);
    if (!file) {
      std::cerr << "Could not open input file: " << argv[2] << '\n';
      return 2;
    }
    input_stream = &file;
  }
  const std::string input(std::istreambuf_iterator<char>{*input_stream}, {});
  try {
    aoc::Result result;
    if (!aoc::solve_day(argv[1], aoc::split_lines(input), result)) {
      std::cerr << "Unknown day: " << argv[1] << '\n';
      return 2;
    }
    std::cout << "Part 1 (" << format_ms(result.part1_ms) << "):\n"
              << result.part1 << '\n';
    print_variants(result, 1);
    std::cout << "Part 2 (" << format_ms(result.part2_ms) << "):\n"
              << result.part2 << '\n';
    print_variants(result, 2);
  } catch (const std::exception& error) {
    std::cerr << "Solution error: " << error.what() << '\n';
    return 1;
  }
  return 0;
}

#endif
