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

void win() {
    printf("%s", getenv("FLAG"));
}

int main() {
    unsigned char buf[16];
    uint64_t v1;
    uint32_t v2_lower, v2_upper;
    
    printf("Welcome to the Value Wrangling Challenge!\n");
    printf("You need to provide 16 bytes as 32 hex characters.\n");
    printf("The first 8 bytes will be interpreted as a 64-bit integer (v1).\n");
    printf("The next 4 bytes as a 32-bit integer (v2_lower), and the last 4 bytes as a 32-bit integer (v2_upper).\n");
    printf("The program computes: result = v1 + (v2_lower * v2_upper)\n");
    printf("If result equals the secret value, you win!\n\n");
    
    printf("Enter 32 hex characters: ");
    char hex_input[33];
    if (fgets(hex_input, sizeof(hex_input), stdin) == NULL) {
        printf("Error reading input.\n");
        exit(1);
    }
    // Remove newline if present
    hex_input[strcspn(hex_input, "\n")] = 0;
    if (strlen(hex_input) != 32) {
        printf("Input must be exactly 32 hex characters.\n");
        exit(1);
    }
    
    // Convert hex string to 16 bytes
    for (int i = 0; i < 16; i++) {
        if (sscanf(hex_input + 2*i, "%2hhx", &buf[i]) != 1) {
            printf("Invalid hex input.\n");
            exit(1);
        }
    }
    
    // Unpack the bytes (assuming little-endian)
    memcpy(&v1, buf, 8);          // First 8 bytes -> 64-bit integer
    memcpy(&v2_lower, buf+8, 4);    // Next 4 bytes -> 32-bit integer
    memcpy(&v2_upper, buf+12, 4);   // Last 4 bytes -> 32-bit integer
    
    uint64_t product = (uint64_t)v2_lower * v2_upper;
    uint64_t result  = v1 + product;
    
    // Secret value: the arithmetic must yield this constant to win.
    uint64_t secret = 0x1122334455667788;
    
    if(result == secret) {
        win();
    } else {
        printf("Nope! v1: 0x%lx, v2_lower: 0x%x, v2_upper: 0x%x\n", v1, v2_lower, v2_upper);
        printf("Product: 0x%lx, result: 0x%lx (expected: 0x%lx)\n", product, result, secret);
    }
    
    return 0;
}
