#!/usr/bin/env python3
"""
compile_to_pyc.py
Compiles all .py files → .pyc and copies them to output folder.
No external dependencies. Works with Python 3.9-3.11.
PHP calls them with: python3 script.pyc
"""

import sys
import os
import py_compile
import shutil
import glob
import struct
import importlib.util
from pathlib import Path

# ---------- CONFIG ----------
SOURCE_DIR = sys.argv[1] if len(sys.argv) > 1 else "./source"
OUTPUT_DIR = sys.argv[2] if len(sys.argv) > 2 else "./dist_pyc"
# ----------------------------

def compile_files(source_dir: str, output_dir: str):
    source_path = Path(source_dir).resolve()
    output_path = Path(output_dir).resolve()

    if not source_path.exists():
        print(f"[ERROR] Source directory not found: {source_path}")
        sys.exit(1)

    output_path.mkdir(parents=True, exist_ok=True)

    py_files = list(source_path.rglob("*.py"))
    if not py_files:
        print(f"[WARN] No .py files found in {source_path}")
        return

    success = 0
    failed = 0

    print(f"{'='*52}")
    print(f" Compiling {len(py_files)} Python file(s) to .pyc")
    print(f" Source : {source_path}")
    print(f" Output : {output_path}")
    print(f"{'='*52}")

    for py_file in py_files:
        # Compute relative path to preserve subfolder structure
        rel = py_file.relative_to(source_path)
        dest_dir = output_path / rel.parent
        dest_dir.mkdir(parents=True, exist_ok=True)

        pyc_name = py_file.stem + ".pyc"
        dest_pyc = dest_dir / pyc_name

        try:
            # Compile to default __pycache__ location first
            py_compile.compile(str(py_file), cfile=str(dest_pyc), doraise=True)
            print(f"  [OK]  {rel.parent / py_file.name}  →  {rel.parent / pyc_name}")
            success += 1
        except py_compile.PyCompileError as e:
            print(f"  [ERR] {py_file.name}: {e}")
            failed += 1

    # Copy any non-.py support files (e.g., .json, .txt, .env)
    for other in source_path.rglob("*"):
        if other.is_file() and other.suffix not in (".py", ".pyc"):
            rel = other.relative_to(source_path)
            dest = output_path / rel
            dest.parent.mkdir(parents=True, exist_ok=True)
            shutil.copy2(other, dest)
            print(f"  [CP]  {rel}  (support file)")

    print(f"\n{'='*52}")
    print(f" Compiled : {success} file(s)")
    if failed:
        print(f" Failed   : {failed} file(s)")
    print(f"\n PHP usage:")
    print(f"   $out = shell_exec('python3 {output_path}/your_script.pyc');")
    print(f"   exec('python3 {output_path}/your_script.pyc', $output);")
    print(f"{'='*52}")

if __name__ == "__main__":
    compile_files(SOURCE_DIR, OUTPUT_DIR)
