#!/usr/bin/env python3
"""
Work Order Z3 - ORIGIN_SEED_SMOKETEST

Test real origin .hx files through hx_v1_rebuild.
"""

import argparse
import json
import sys
import tempfile
from pathlib import Path
from datetime import datetime

# Add parent to path for imports
sys.path.insert(0, str(Path(__file__).parent.parent))

from hx_v1_rebuild.hx_parser_v1 import parse_hx
from hx_v1_rebuild.hx_to_py_v1 import compile_to_python
from hx_v1_rebuild.helix_encode_v1 import encode_to_helix, write_hxz

RECEIPTS = Path("/home/voidstr3m33/helix-cdc/receipts")


def run_smoketest(hx_path: Path) -> dict:
    """Run full pipeline on an origin .hx file."""
    result = {
        "hx_path": str(hx_path),
        "hx_name": hx_path.name,
        "timestamp": datetime.now().isoformat(),
        "parse_ok": False,
        "compile_ok": False,
        "exec_ok": False,
        "encode_ok": False,
        "errors": [],
        "ir_summary": None,
        "runtime_state": None,
        "hxz_size": None,
    }

    # Read file
    if not hx_path.exists():
        result["errors"].append(f"File not found: {hx_path}")
        return result

    try:
        source = hx_path.read_text(encoding='utf-8', errors='ignore')
        result["source_size"] = len(source)
        result["source_lines"] = len(source.split('\n'))
        result["source_preview"] = source[:200]
    except Exception as e:
        result["errors"].append(f"Read error: {e}")
        return result

    # Try to parse
    try:
        program = parse_hx(source, filename=hx_path.stem)
        result["parse_ok"] = True
        result["ir_summary"] = {
            "soulfile_name": program.soulfile_name,
            "slots_count": len(program.slots),
            "vows_count": len(program.vows),
            "steps_count": len(program.steps),
            "slots": [s.name for s in program.slots],
            "vows": [v.name for v in program.vows],
            "steps": [s.name for s in program.steps],
        }
    except Exception as e:
        result["errors"].append(f"Parse error: {e}")
        # Try to identify which lines failed
        for i, line in enumerate(source.split('\n')[:20]):
            if line.strip() and not line.strip().startswith('#'):
                result["errors"].append(f"  Line {i+1}: {line[:50]}")
        return result

    # Try to compile to Python
    try:
        py_code = compile_to_python(program)
        result["compile_ok"] = True
        result["py_code_size"] = len(py_code)
    except Exception as e:
        result["errors"].append(f"Compile error: {e}")
        return result

    # Try to execute
    try:
        namespace = {}
        exec(py_code, namespace)
        runtime_result = namespace["run"]()
        result["exec_ok"] = True
        result["runtime_state"] = {
            "soulfile": runtime_result.get("soulfile"),
            "slots_initialized": list(runtime_result.get("slots", {}).keys()),
            "vows_active": list(runtime_result.get("vows_active", set())),
            "steps_executed": runtime_result.get("steps_executed", []),
        }
    except Exception as e:
        result["errors"].append(f"Exec error: {e}")
        # Still try to encode even if exec fails

    # Try to encode + compress
    try:
        encoded = encode_to_helix(program)
        with tempfile.TemporaryDirectory() as tmpdir:
            hxz_path = Path(tmpdir) / f"{hx_path.stem}.hxz"
            write_hxz(hxz_path, encoded)
            result["encode_ok"] = True
            result["hxz_size"] = hxz_path.stat().st_size
    except Exception as e:
        result["errors"].append(f"Encode error: {e}")

    return result


def main():
    parser = argparse.ArgumentParser(description="Test origin .hx files through hx_v1_rebuild")
    parser.add_argument("--hx-path", required=True, help="Path to .hx file")
    args = parser.parse_args()

    hx_path = Path(args.hx_path)
    print(f"Running origin seed smoketest on: {hx_path.name}")

    result = run_smoketest(hx_path)

    # Print summary
    print(f"\n=== Results ===")
    print(f"Parse: {'OK' if result['parse_ok'] else 'FAIL'}")
    print(f"Compile: {'OK' if result['compile_ok'] else 'FAIL'}")
    print(f"Exec: {'OK' if result['exec_ok'] else 'FAIL'}")
    print(f"Encode: {'OK' if result['encode_ok'] else 'FAIL'}")

    if result["ir_summary"]:
        print(f"\nIR Summary:")
        print(f"  Slots: {result['ir_summary']['slots_count']}")
        print(f"  Vows: {result['ir_summary']['vows_count']}")
        print(f"  Steps: {result['ir_summary']['steps_count']}")

    if result["errors"]:
        print(f"\nErrors:")
        for e in result["errors"][:10]:
            print(f"  {e}")

    # Write receipt
    receipt_name = f"origin_seed_smoketest_{hx_path.stem}.json"
    receipt_path = RECEIPTS / receipt_name
    with open(receipt_path, 'w') as f:
        json.dump(result, f, indent=2)
    print(f"\nWrote: {receipt_path}")

    # Return exit code
    if result["parse_ok"] and result["encode_ok"]:
        return 0
    return 1


if __name__ == "__main__":
    sys.exit(main())
