from pathlib import Path

Import("env")

project_dir = Path(env.subst("$PROJECT_DIR"))
source_name = env.GetProjectOption("custom_text_source", "texts/If.txt")
source_path = Path(source_name)
if not source_path.is_absolute():
    source_path = project_dir / source_path

if not source_path.exists():
    raise RuntimeError(f"custom_text_source file not found: {source_path}")

data = source_path.read_bytes()
generated_dir = Path(env.subst("$BUILD_DIR")) / "generated"
generated_dir.mkdir(parents=True, exist_ok=True)
header_path = generated_dir / "SelectedText.h"
symbol_name = source_path.name.replace("\\", "/")

lines = [
    "#pragma once",
    "",
    "#include <stddef.h>",
    "#include <stdint.h>",
    "",
    "#if defined(ARDUINO)",
    "#include <Arduino.h>",
    "#include <pgmspace.h>",
    "#else",
    "#ifndef PROGMEM",
    "#define PROGMEM",
    "#endif",
    "#ifndef pgm_read_byte",
    "#define pgm_read_byte(addr) (*(const uint8_t*)(addr))",
    "#endif",
    "#endif",
    "",
    f'static constexpr const char* SELECTED_TEXT_NAME = "{symbol_name}";',
    f"static constexpr size_t SELECTED_TEXT_SIZE = {len(data)};",
    "static const uint8_t SELECTED_TEXT[] PROGMEM = {",
]

for offset in range(0, len(data), 16):
    chunk = data[offset : offset + 16]
    values = ", ".join(f"0x{byte:02x}" for byte in chunk)
    lines.append(f"  {values},")

lines.extend(
    [
        "};",
        "",
        "static inline uint8_t read_selected_text_byte(size_t offset) {",
        "  return pgm_read_byte(SELECTED_TEXT + offset);",
        "}",
        "",
    ]
)

header_path.write_text("\n".join(lines))
env.Append(CPPPATH=[str(generated_dir)])
print(f"Embedded {source_path} ({len(data)} bytes) -> {header_path}")
