/*
 * serial_parser.h - Parse serial.log text files and identify boot stages.
 *
 * Reads the QEMU serial console capture and classifies each line into a
 * boot stage (firmware → bootloader → kernel → hardware → userspace → login).
 */

#ifndef SERIAL_PARSER_H
#define SERIAL_PARSER_H

#include <stdint.h>
#include <stddef.h>
#include <stdio.h>

/* Boot progression stages (ordered by typical sequence). */
typedef enum {
    STAGE_UNKNOWN = 0,
    STAGE_FIRMWARE,      /* UEFI / OVMF initialization */
    STAGE_BOOTLOADER,    /* GRUB / systemd-boot */
    STAGE_KERNEL_INIT,   /* "Linux version", "Booting Linux" */
    STAGE_HARDWARE_INIT, /* hardware detection messages */
    STAGE_USERSPACE,     /* systemd / init starting */
    STAGE_LOGIN,         /* login prompt */
    STAGE_COMPLETE,      /* boot finished */
    STAGE_ERROR,         /* panic, oops, BUG */
    STAGE_COUNT          /* sentinel — number of stages */
} boot_stage_t;

/* Human-readable names for each stage (indexed by boot_stage_t). */
extern const char *boot_stage_names[STAGE_COUNT];

/* A single serial-log line (node in a singly-linked list). */
typedef struct serial_line {
    char *text;                   /* malloc'd line content (no trailing \n) */
    boot_stage_t stage;
    struct serial_line *next;
} serial_line_t;

/* Aggregate statistics over all parsed lines. */
typedef struct serial_summary {
    serial_line_t *lines;         /* linked-list head */
    size_t total_lines;
    size_t lines_per_stage[STAGE_COUNT];
    boot_stage_t final_stage;     /* highest stage reached (or STAGE_ERROR) */
    char error_messages[8][256];  /* up to 8 error lines */
    int error_count;
    uint64_t boot_duration_ms;    /* estimated from [X.XXXXXX] timestamps */
} serial_summary_t;

/*
 * Parse a serial console log.
 * Returns 0 on success, -1 on error (file not found, read failure).
 * Caller must call serial_free_summary() to release memory.
 */
int  serial_parse_file(const char *path, serial_summary_t *summary);

/* Free all dynamically-allocated memory in *summary. */
void serial_free_summary(serial_summary_t *summary);

/* Print per-stage line counts and boot duration. */
void serial_print_stages(const serial_summary_t *summary, FILE *out);

/* Print a human-readable summary. */
void serial_print_text(const serial_summary_t *summary, FILE *out);

#endif /* SERIAL_PARSER_H */
