// SPDX-License-Identifier: GPL-2.0-only
/*
 *  ppm/src/cmd/search.c
 *
 *  Substring search across registry package names.
 *
 *  Copyright (C) 2026 Project Tick
 */

#include <ppm/registry.h>

#include <stdio.h>
#include <stdlib.h>

#include "../cli.h"
#include "../util/log.h"
#include "common.h"

int ppm_cmd_search(int argc, char **argv) {
    const char *query = (argc > 1) ? argv[1] : "";

    ppm_registry_t *reg = NULL;
    if (ppm_cmd_open_registry(&reg) != PPM_OK) {
        ppm_error("could not open registry");
        return 1;
    }

    char **names = NULL;
    size_t n = 0;
    ppm_error_t err = ppm_registry_search(reg, query, &names, &n);
    if (err) {
        ppm_error("search: %s", ppm_strerror(err));
        ppm_registry_close(reg);
        return 1;
    }
    for (size_t i = 0; i < n; i++) {
        ppm_version_t *vs = NULL;
        size_t vn = 0;
        if (ppm_registry_versions(reg, names[i], &vs, &vn) == PPM_OK && vn) {
            printf("%-30s  %u.%u.%u\n", names[i],
                   vs[0].major, vs[0].minor, vs[0].patch);
        } else {
            printf("%s\n", names[i]);
        }
        free(vs);
        free(names[i]);
    }
    free(names);

    if (n == 0) ppm_info("no matches for '%s'", query);
    ppm_registry_close(reg);
    return 0;
}
