#include "ck/find/search_backend.hpp"
#include "ck/find/search_model.hpp"

#include <algorithm>
#include <chrono>
#include <cstdio>
#include <filesystem>
#include <fstream>
#include <gtest/gtest.h>
#include <string>
#include <vector>

TEST(SearchBackend, BuildsDefaultFindCommand)
{
    auto spec = ck::find::makeDefaultSpecification();
    auto command = ck::find::buildFindCommand(spec);
    std::vector<std::string> expected = {"find", ".", "-P", "!", "-name", ".*", "!", "-path", "*/.*", "-print"};
    EXPECT_EQ(command, expected);
}

TEST(SearchBackend, HiddenFilterRespectsConfiguration)
{
    auto spec = ck::find::makeDefaultSpecification();
    spec.includeHidden = true;
    auto command = ck::find::buildFindCommand(spec);
    std::vector<std::string> hidden = {"!", "-name", ".*"};
    EXPECT_EQ(std::search(command.begin(), command.end(), hidden.begin(), hidden.end()), command.end());

    spec.includeHidden = false;
    auto filtered = ck::find::buildFindCommand(spec);
    EXPECT_NE(std::search(filtered.begin(), filtered.end(), hidden.begin(), hidden.end()), filtered.end());
}

TEST(SearchBackend, NormalisesSpecificationNames)
{
    EXPECT_EQ(ck::find::normaliseSpecificationName("  Example Spec  "), "Example Spec");
    EXPECT_EQ(ck::find::normaliseSpecificationName("\t\n"), "");
}

TEST(SearchBackend, ExecutesSpecificationWithoutExternalFind)
{
    namespace fs = std::filesystem;
    fs::path tempDir = fs::temp_directory_path() /
                       fs::path("ck-find-backend-test-" + std::to_string(std::chrono::steady_clock::now().time_since_epoch().count()));
    fs::create_directories(tempDir);

    fs::path textFile = tempDir / "example.txt";
    {
        std::ofstream stream(textFile);
        stream << "hello world" << std::endl;
    }

    fs::path hiddenFile = tempDir / ".ignored";
    {
        std::ofstream stream(hiddenFile);
        stream << "secret" << std::endl;
    }

    auto spec = ck::find::makeDefaultSpecification();
    std::snprintf(spec.startLocation.data(), spec.startLocation.size(), "%s", tempDir.string().c_str());
    std::snprintf(spec.searchText.data(), spec.searchText.size(), "%s", "hello");
    spec.textOptions.searchInContents = true;
    spec.textOptions.searchInFileNames = false;
    spec.includeHidden = false;

    ck::find::SearchExecutionOptions options;
    options.includeActions = false;
    options.captureMatches = true;
    options.filterContent = true;

    auto result = ck::find::executeSpecification(spec, options, nullptr, nullptr);
    EXPECT_EQ(result.exitCode, 0);
    EXPECT_EQ(result.matchCount, 1u);
    ASSERT_EQ(result.matches.size(), 1u);
    EXPECT_EQ(result.matches.front(), textFile);

    fs::remove(hiddenFile);
    fs::remove(textFile);
    fs::remove_all(tempDir);
}

TEST(SearchBackend, ReportsCancellationAtTraversalBoundaries)
{
    namespace fs = std::filesystem;
    fs::path tempDir = fs::temp_directory_path() /
                       fs::path("ck-find-cancel-test-" + std::to_string(std::chrono::steady_clock::now().time_since_epoch().count()));
    fs::create_directories(tempDir);
    for (int index = 0; index < 8; ++index)
    {
        std::ofstream stream(tempDir / ("item-" + std::to_string(index) + ".txt"));
        stream << "match" << std::endl;
    }

    auto spec = ck::find::makeDefaultSpecification();
    std::snprintf(spec.startLocation.data(), spec.startLocation.size(), "%s", tempDir.string().c_str());
    bool cancel = false;
    ck::find::SearchExecutionOptions options;
    options.captureMatches = true;
    options.cancellation_requested = [&cancel] { return cancel; };
    options.on_match = [&cancel](const fs::path &) { cancel = true; };

    auto result = ck::find::executeSpecification(spec, options, nullptr, nullptr);
    EXPECT_TRUE(result.cancelled);
    EXPECT_EQ(result.exitCode, 130);
    EXPECT_EQ(result.matchCount, 1u);
    EXPECT_LE(result.matches.size(), 1u);

    fs::remove_all(tempDir);
}

TEST(SearchBackend, FilenameOrContentMatchesEitherWhenBothTargetsEnabled)
{
    namespace fs = std::filesystem;
    fs::path tempDir = fs::temp_directory_path() /
                       fs::path("ck-find-or-test-" + std::to_string(std::chrono::steady_clock::now().time_since_epoch().count()));
    fs::create_directories(tempDir);

    fs::path byContent = tempDir / "unrelated_name.cpp";
    {
        std::ofstream stream(byContent);
        stream << "int special_token = 42;\n";
    }

    fs::path byName = tempDir / "special_token_helper.cpp";
    {
        std::ofstream stream(byName);
        stream << "// empty\n";
    }

    fs::path neither = tempDir / "other.cpp";
    {
        std::ofstream stream(neither);
        stream << "int x = 0;\n";
    }

    auto spec = ck::find::makeDefaultSpecification();
    std::snprintf(spec.startLocation.data(), spec.startLocation.size(), "%s", tempDir.string().c_str());
    std::snprintf(spec.searchText.data(), spec.searchText.size(), "%s", "special_token");
    spec.enableTextSearch = true;
    spec.textOptions.searchInContents = true;
    spec.textOptions.searchInFileNames = true;

    ck::find::SearchExecutionOptions options;
    options.includeActions = false;
    options.captureMatches = true;
    options.filterContent = true;
    std::size_t progressCalls = 0;
    options.on_progress = [&progressCalls](const ck::find::SearchProgressSnapshot &) { ++progressCalls; };

    auto result = ck::find::executeSpecification(spec, options, nullptr, nullptr);
    EXPECT_EQ(result.exitCode, 0);
    EXPECT_EQ(result.matchCount, 2u);
    EXPECT_EQ(result.matchEntries.size(), 2u);
    EXPECT_GT(progressCalls, 0u);
    EXPECT_NE(std::find(result.matches.begin(), result.matches.end(), byContent), result.matches.end());
    EXPECT_NE(std::find(result.matches.begin(), result.matches.end(), byName), result.matches.end());

    fs::remove_all(tempDir);
}

TEST(SearchBackend, CustomDateRangeFiltersEntries)
{
    namespace fs = std::filesystem;
    fs::path tempDir = fs::temp_directory_path() /
                       fs::path("ck-find-date-test-" + std::to_string(std::chrono::steady_clock::now().time_since_epoch().count()));
    fs::create_directories(tempDir);

    fs::path todayFile = tempDir / "today.txt";
    {
        std::ofstream stream(todayFile);
        stream << "recent\n";
    }

    auto spec = ck::find::makeDefaultSpecification();
    std::snprintf(spec.startLocation.data(), spec.startLocation.size(), "%s", tempDir.string().c_str());
    spec.enableTextSearch = false;
    spec.enableTimeFilters = true;
    spec.timeOptions.preset = ck::find::TimeFilterOptions::Preset::CustomRange;
    std::snprintf(spec.timeOptions.customFrom.data(), spec.timeOptions.customFrom.size(), "2000-01-01");
    std::snprintf(spec.timeOptions.customTo.data(), spec.timeOptions.customTo.size(), "2000-12-31");

    ck::find::SearchExecutionOptions options;
    options.includeActions = false;
    options.captureMatches = true;
    auto excluded = ck::find::executeSpecification(spec, options, nullptr, nullptr);
    EXPECT_EQ(excluded.matchCount, 0u);

    std::snprintf(spec.timeOptions.customTo.data(), spec.timeOptions.customTo.size(), "2099-12-31");
    auto included = ck::find::executeSpecification(spec, options, nullptr, nullptr);
    EXPECT_EQ(included.matchCount, 1u);

    fs::remove_all(tempDir);
}
