// SPDX-License-Identifier: GPL-2.0-only
/*
 *  ppm/src/cmd/remove.c
 *
 *  Drop a top-level dependency from ppm.toml and run a fresh resolve
 *  through the install pipeline. The transitive deps of the removed
 *  package will fall out of the new lockfile automatically because the
 *  resolver only keeps what is still reachable from the root.
 *
 *  Copyright (C) 2026 Project Tick
 */

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

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

/* Defined in install.c; re-running install after editing the manifest
 * is the simplest correct implementation. */
int ppm_cmd_install(int argc, char **argv);

static int drop_dependency_line(const char *name) {
    FILE *r = fopen("ppm.toml", "r");
    if (!r) { ppm_error("remove: cannot read ppm.toml"); return -1; }
    FILE *w = fopen("ppm.toml.new", "w");
    if (!w) { fclose(r); ppm_error("remove: cannot create ppm.toml.new"); return -1; }

    char line[4096];
    int dropped = 0;
    size_t nlen = strlen(name);
    while (fgets(line, sizeof(line), r)) {
        /* Skip lines matching "<name> = " (with optional leading whitespace). */
        const char *p = line;
        while (*p == ' ' || *p == '\t') p++;
        if (strncmp(p, name, nlen) == 0) {
            const char *q = p + nlen;
            while (*q == ' ' || *q == '\t') q++;
            if (*q == '=') { dropped = 1; continue; }
        }
        fputs(line, w);
    }
    fclose(r);
    fclose(w);
    if (rename("ppm.toml.new", "ppm.toml") != 0) {
        ppm_error("remove: rename failed");
        return -1;
    }
    return dropped ? 1 : 0;
}

int ppm_cmd_remove(int argc, char **argv) {
    if (argc < 2) {
        ppm_error("usage: ppm remove <pkg>...");
        return 2;
    }
    int any = 0;
    for (int i = 1; i < argc; i++) {
        int rc = drop_dependency_line(argv[i]);
        if (rc < 0) return 1;
        if (rc == 0) {
            ppm_warn("remove: '%s' is not a direct dependency", argv[i]);
        } else {
            any = 1;
            ppm_info("removed '%s' from ppm.toml", argv[i]);
        }
    }
    if (!any) return 0;

    /* Re-run install with no extra args to re-resolve from the trimmed
     * manifest. The transaction layer will produce a new generation. */
    char *fake_argv[] = { (char *)"install", NULL };
    return ppm_cmd_install(1, fake_argv);
}
