import re
from pathlib import Path

# Zig's C backend mangles struct names (e.g. instrument_hooks_InstrumentHooks__547),
# and there's no way to control this from Zig source. Replace with the stable
# name from core.h so that core.c can be included alongside core.h without
# type conflicts.
REPLACEMENTS = [
    (
        re.compile(r"struct instrument_hooks_InstrumentHooks__\d+"),
        "struct InstrumentHooks",
    ),
]


def load_transpiled(path: Path) -> str:
    content = path.read_text()
    print(f"Read {path} ({len(content.splitlines())} lines)")
    for pattern, replacement in REPLACEMENTS:
        match = pattern.search(content)
        if not match:
            raise RuntimeError(f"Pattern not found in {path}: {pattern.pattern}")
        count = len(pattern.findall(content))
        print(f"  {match.group(0):>50s}  ->  {replacement}  ({count} occurrences)")
        content = pattern.sub(replacement, content)
    # Add core.h include at the top so consumers get the constants
    # (MARKER_TYPE_*) and inline helpers from core.h automatically.
    return '#include "core.h"\n' + content


linux_c = load_transpiled(Path("zig-out/lib/core.linux.c"))
macos_c = load_transpiled(Path("zig-out/lib/core.macos.c"))
valgrind_wrapper = Path("src/helpers/valgrind_wrapper.c").read_text()
windows_stub = Path("scripts/stub.c").read_text()

TEMPLATE = f"""\
// This file is generated by scripts/release.py
// Do not edit it manually.

// Include compatibility layer for cross-platform support
#include "compat.h"

#if defined(_WIN32)
{windows_stub}
#elif defined(__APPLE__)
{macos_c}
#else
{linux_c}
#endif
{valgrind_wrapper}
"""

Path("dist/core.c").write_text(TEMPLATE)
print(f"\nWrote dist/core.c ({len(TEMPLATE.splitlines())} lines)")
