# util.py
import py_compile, compileall, os, sys
from pathlib import Path
from typing import Optional

def compile_file(src: str, dest: Optional[str] = None, optimize: int = -1) -> str:
    src_path = Path(src)
    if not src_path.exists():
        raise FileNotFoundError(f"source file not found: {src}")
    if src_path.suffix != ".py":
        raise ValueError("src must be a .py file")
    if dest:
        dest_path = Path(dest)
        dest_path.parent.mkdir(parents=True, exist_ok=True)
        py_compile.compile(str(src_path), cfile=str(dest_path), optimize=optimize)
        return str(dest_path)
    else:
        py_compile.compile(str(src_path), optimize=optimize)
        pycache = src_path.parent / "__pycache__"
        if pycache.exists():
            name_prefix = src_path.stem
            for f in pycache.iterdir():
                if f.name.startswith(name_prefix) and f.suffix == ".pyc":
                    return str(f)
        sibling = src_path.with_suffix('.pyc')
        if sibling.exists():
            return str(sibling)
        return str(src_path.with_suffix('.pyc'))

def compile_directory(path: str, force: bool = False, optimize: int = -1) -> int:
    p = Path(path)
    if not p.is_dir():
        raise NotADirectoryError(path)
    success = compileall.compile_dir(str(p), force=force, optimize=optimize, quiet=1)
    return 1 if success else 0
