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

/* EXI codec headers */
#include "iso1EXIDatatypes.h"
#include "iso1EXIDatatypesEncoder.h"
#include "ByteStream.h"

#define BUFFER_SIZE 1024

int main() {
    struct iso1EXIDocument exiDoc;
    bitstream_t stream;
    uint8_t buffer[BUFFER_SIZE];
    size_t pos = 0;
    int errn = 0;
    
    /* Initialize EXI document */
    init_iso1EXIDocument(&exiDoc);
    
    /* Create a simple V2G message */
    exiDoc.V2G_Message_isUsed = 1;
    init_iso1MessageHeaderType(&exiDoc.V2G_Message.Header);
    
    /* Set session ID to all zeros */
    memset(exiDoc.V2G_Message.Header.SessionID.bytes, 0, 8);
    exiDoc.V2G_Message.Header.SessionID.bytesLen = 8;
    
    /* Create session setup request */
    exiDoc.V2G_Message.Body.SessionSetupReq_isUsed = 1;
    init_iso1SessionSetupReqType(&exiDoc.V2G_Message.Body.SessionSetupReq);
    
    /* Set EVCC ID */
    strcpy((char*)exiDoc.V2G_Message.Body.SessionSetupReq.EVCCID.bytes, "01");
    exiDoc.V2G_Message.Body.SessionSetupReq.EVCCID.bytesLen = 2;
    
    /* Setup output stream */
    stream.size = BUFFER_SIZE;
    stream.data = buffer;
    stream.pos = &pos;
    stream.buffer = 0;
    stream.capacity = 8;
    
    /* Encode to EXI */
    printf("Encoding V2G message to EXI...\n");
    errn = encode_iso1ExiDocument(&stream, &exiDoc);
    
    if (errn != 0) {
        printf("Encoding failed with error: %d\n", errn);
        return -1;
    }
    
    /* Write to file */
    FILE *fp = fopen("test_message.exi", "wb");
    if (fp == NULL) {
        printf("Cannot create output file\n");
        return -1;
    }
    
    fwrite(buffer, 1, pos, fp);
    fclose(fp);
    
    printf("Created test_message.exi with %zu bytes\n", pos);
    return 0;
}