// Written by retoor@molodetz.nl

// This program allows for the searching and indexing of text content via a SQLite database, using FTS5 for efficient text-based queries.

// Non-standard imports include sqlite3 for database operations and jansson to manage JSON output, enhancing the program's functionality beyond basic C capabilities.

// The MIT License (MIT)

// Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:

// The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.

// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sqlite3.h>
#include <stdbool.h>
#include <jansson.h>

#define MAX_WORDS 10
#define MAX_LENGTH 256

void format_search_query(const char *input, char *output) {
    char temp[MAX_LENGTH];
    strncpy(temp, input, MAX_LENGTH);
    temp[MAX_LENGTH - 1] = '\0';
    output[0] = '\0';
    char *words[MAX_WORDS];
    int count = 0;

    char *token = strtok(temp, " ");
    while (token != NULL && count < MAX_WORDS) {
        words[count++] = token;
        token = strtok(NULL, " ");
    }

    char *ptr = output;
    for (int i = 0; i < count; i++) {
        ptr += sprintf(ptr, "\"*%s*\"", words[i]);
        if (i < count - 1) {
            ptr += sprintf(ptr, " OR ");
        }
    }
}

int search(const sqlite3 *db, const char *search_query) {
    if (!strcmp(search_query, "_") || !strcmp(search_query, ".") || !strcmp(search_query, "false") || !strcmp(search_query, "null")) {
        return -1;
    }
    
    char optimized_search_query[strlen(search_query) * 3];
    format_search_query(search_query, optimized_search_query);

    const char *select_sql = "SELECT path, line_number, content, bm25(docs) as rank FROM docs WHERE docs MATCH ? ORDER BY rank;";
    sqlite3_stmt *select_stmt;
    int rc = sqlite3_prepare_v2(db, select_sql, -1, &select_stmt, NULL);
    if (rc != SQLITE_OK) {
        fprintf(stderr, "Failed to prepare select statement: %s\n", sqlite3_errmsg(db));
        sqlite3_close(db);
        return -2;
    }
    sqlite3_bind_text(select_stmt, 1, optimized_search_query, -1, SQLITE_TRANSIENT);
    
    json_t *results = json_array();
    fprintf(stderr,"\nFound: \"%s\"\n", optimized_search_query);
    int result = 0;
    while ((rc = sqlite3_step(select_stmt)) == SQLITE_ROW) {
        const unsigned char *file = sqlite3_column_text(select_stmt, 0);
        const unsigned char *content = sqlite3_column_text(select_stmt, 2);
        int line_num = sqlite3_column_int(select_stmt, 1);
        
        json_t *entry = json_object();
        json_object_set_new(entry, "path", json_string((const char *)file));
        json_object_set_new(entry, "line_number", json_integer(line_num));
        json_object_set_new(entry, "content", json_string((const char *)content));
        json_object_set_new(entry, "rank", json_real(sqlite3_column_double(select_stmt, 3)));
        json_array_append_new(results, entry);
        
        result++;
    }
    
    if (rc != SQLITE_DONE) {
        fprintf(stderr, "Error: %s\n", sqlite3_errmsg(db));
    }
    
    char *json_output = json_dumps(results, JSON_INDENT(4));
    printf("%s\n", json_output);
    json_decref(results);
    sqlite3_finalize(select_stmt);
    return result;
}

int main(int argc, char *argv[]) {
    if (argc < 2) {
        fprintf(stderr, "Usage: %s <search_query> <file1> [file2 ...]\n", argv[0]);
        return EXIT_FAILURE;
    }
    
    const char *search_query = argv[1];
    sqlite3 *db;
    int rc = sqlite3_open("ft.db", &db);
    if (rc != SQLITE_OK) {
        fprintf(stderr, "Cannot open database: %s\n", sqlite3_errmsg(db));
        return EXIT_FAILURE;
    }
    
    const char *create_table_sql = "CREATE VIRTUAL TABLE IF NOT EXISTS docs USING fts5(path, line_number, content, tokenize='porter');";
    rc = sqlite3_exec(db, create_table_sql, NULL, NULL, NULL);
    
    if (rc != SQLITE_OK) {
        fprintf(stderr, "Error: %s\n", sqlite3_errmsg(db));
        sqlite3_close(db);
        return EXIT_FAILURE;
    }
    
    const char *insert_sql = "INSERT INTO docs (path, line_number, content) VALUES (?, ?, ?);";
    sqlite3_stmt *insert_stmt;
    rc = sqlite3_prepare_v2(db, insert_sql, -1, &insert_stmt, NULL);
    
    if (rc != SQLITE_OK) {
        fprintf(stderr, "Failed to prepare insert statement: %s\n", sqlite3_errmsg(db));
        sqlite3_close(db);
        return EXIT_FAILURE;
    }
    
    bool file_mode = false;
    for (int i = 2; i < argc; i++) {
        if (!strcmp(argv[i], "-f")) file_mode = true;
        if (!strncmp(argv[i], "-", 1)) continue;
        
        const char *filename = argv[i];
        FILE *fp = fopen(filename, "r");
        if (!fp) {
            perror(filename);
            continue;
        }
        
        fprintf(stderr, "Indexing: %s\n", filename);
        if (file_mode) {
            fseek(fp, 0, SEEK_END);
            size_t len = ftell(fp);
            fseek(fp, 0, SEEK_SET);
            char *buffer = malloc(len + 1);
            ssize_t read = fread(buffer, 1, len, fp);
            buffer[read] = '\0';
            sqlite3_reset(insert_stmt);
            sqlite3_bind_text(insert_stmt, 1, filename, -1, SQLITE_TRANSIENT);
            sqlite3_bind_int(insert_stmt, 2, 1);
            sqlite3_bind_text(insert_stmt, 3, buffer, -1, SQLITE_TRANSIENT);
            rc = sqlite3_step(insert_stmt);
            if (rc != SQLITE_DONE) {
                fprintf(stderr, "Insert failed: %s\n", sqlite3_errmsg(db));
            }
            free(buffer);
        } else {
            char *line = NULL;
            size_t len = 0;
            ssize_t read;
            int line_number = 0;
            
            while ((read = getline(&line, &len, fp)) != -1) {
                line_number++;
                sqlite3_reset(insert_stmt);
                sqlite3_bind_text(insert_stmt, 1, filename, -1, SQLITE_TRANSIENT);
                sqlite3_bind_int(insert_stmt, 2, line_number);
                sqlite3_bind_text(insert_stmt, 3, line, -1, SQLITE_TRANSIENT);
                rc = sqlite3_step(insert_stmt);
                if (rc != SQLITE_DONE) {
                    fprintf(stderr, "Insert failed: %s\n", sqlite3_errmsg(db));
                }
            }
            free(line);
        }
        fclose(fp);
    }
    
    sqlite3_finalize(insert_stmt);
    int result_count = search(db, search_query);
    if (result_count == -2) {
        fprintf(stderr, "Search failed: %s\n", sqlite3_errmsg(db));
    } else if (result_count >= 0) {
        fprintf(stderr,"Total: %d\n", result_count);
    }
    
    sqlite3_close(db);
    return result_count > -2 ? EXIT_SUCCESS : EXIT_FAILURE;
}
