from pathlib import Path from typing import Optional from .segmenter import SourceSegmenter from .compressor import GXCompressor, CompressionError from .manifest_builder import ManifestBuilder from .gx_packer import GXPacker, PackingError class CompilerError(Exception): pass class GXCompiler: @staticmethod def compile_to_gx( source_path: str, output_path: str, source_type: str = ".py", version: str = "1.0.0", contributor: str = "GlyphRunner", verbose: bool = False ) -> None: try: source_file = Path(source_path) output_file = Path(output_path) if verbose: print(f"[COMPILE] Reading source: {source_file}") if not source_file.exists(): raise CompilerError(f"Source file not found: {source_file}") source_code = source_file.read_text(encoding='utf-8') if verbose: print(f"[COMPILE] Segmenting source") segments = SourceSegmenter.segment(source_code) segment_metas = [] for seg in segments: segment_metas.append({ "id": seg.segment_id, "start": seg.start_line, "end": seg.end_line, "start_byte": seg.start_byte, "end_byte": seg.end_byte }) if verbose: print(f"[COMPILE] Compressing {len(segments)} segments") try: compressed = GXCompressor.compress(source_code) except CompressionError as e: raise CompilerError(f"Compression failed: {e}") if verbose: print(f"[COMPILE] Building manifest") manifest = ManifestBuilder.build( source_file=str(source_file), source_type=source_type, segments=segment_metas, version=version, contributor=contributor ) if verbose: print(f"[COMPILE] Packing GX file") try: gx_data = GXPacker.pack(manifest, compressed) except PackingError as e: raise CompilerError(f"Packing failed: {e}") output_file.parent.mkdir(parents=True, exist_ok=True) output_file.write_bytes(gx_data) if verbose: print(f"[COMPILE] Done: {output_file}") except CompilerError: raise except Exception as e: raise CompilerError(f"Compilation failed: {e}")