#include <stdio.h>
#include <string.h>
#define VERSION "0.0.1"
int main(int argc, char *argv[]) {
    if (argc > 1 && (strcmp(argv[1], "-v") == 0 || strcmp(argv[1], "--version") == 0)) {
        printf("cfetch version %s\n", VERSION);
        return 0;
    }
    const char *cpu_file_path = "/proc/cpuinfo";
    const char *mem_file_path = "/proc/meminfo";
    const char *os_file_path = "/etc/os-release";
    char line[256];
    char cpu_cname[256];
    int j = 0;
    char os_name[256];
    char cpu_name[256];
    unsigned long long mem_total;
    unsigned long long mem_avail;
    float mem_total_gb;
    float mem_used_prc;
    float mem_used_gb;

    FILE *cpufile = fopen(cpu_file_path, "r");
    if (cpufile == NULL) {
        printf("Error opening file /proc/cpuinfo!\n");
        return 1;
    }
    while (fgets(line, sizeof(line), cpufile) != NULL) {
        if (strstr(line, "model name") != NULL) {
            sscanf(line, "model name : %[^\n]", cpu_name);
            break;
        }
    }
    fclose(cpufile);
    for (int i = 0; cpu_name[i] != '\0'; i++) {
        if (cpu_name[i] != ' ' || (i > 0 && cpu_name[i-1] != ' ')) {
            cpu_cname[j] = cpu_name[i];
            j++;
        }
    }
    cpu_cname[j] = '\0';
    strcpy(cpu_name, cpu_cname);


    FILE *memfile = fopen(mem_file_path, "r");
    if (memfile == NULL) {
        printf("Failed opening file /proc/meminfo!\n");
        return 1;
    }
    while (fgets(line, sizeof(line), memfile) != NULL) {
        if (strstr(line, "MemTotal") != NULL) {
            sscanf(line, "MemTotal: %llu", &mem_total);
        }
        if (strstr(line, "MemAvailable") != NULL) {
            sscanf(line, "MemAvailable: %llu", &mem_avail);
        }

    }
    fclose(memfile);

    FILE *osfile = fopen(os_file_path, "r");
    if (osfile == NULL) {
        printf("Failed opening file /etc/os-release!\n");
        return 1;
    }
    while (fgets(line, sizeof(line), osfile) != NULL) {
        if (strstr(line, "PRETTY_NAME") != NULL) {
            sscanf(line, "PRETTY_NAME=\"%[^\"]\"", os_name);
            break;
        }
    }
    fclose(osfile);
    
    mem_total_gb = mem_total / 1048576.0f;
    mem_used_gb = (mem_total - mem_avail) / 1048576.0f;
    mem_used_prc = ((float)(mem_total - mem_avail) / mem_total) * 100.0f;
    
    printf("OS name: %s\n", os_name);
    printf("CPU name: %s\n", cpu_cname);
    printf("Memory: %.2f GiB / ", mem_used_gb);
    printf("%.2f GiB ", mem_total_gb);
    printf("(%.0f%%)\n", mem_used_prc);  
    return 0;

}
