#!/usr/bin/env python3
"""
echo_mmlu_worker.py - Worker script for Echo MMLU inference via FibPi daemon
=============================================================================

Called by fibpi_wave_daemon to run Echo MMLU inference jobs.

Job format (daemon passes these as CLI args):
    --question "What is the capital of France?"
    --mode full|no_reflex|no_retrieval|no_fibpi3d|minimal
    --model ~/mistral_canonical_decoded.gguf
    --out /tmp/echo_result_123.json

Output format (JSON):
    {
        "question": "What is the capital of France?",
        "answer": "The capital of France is Paris.",
        "mode": "full",
        "duration_s": 420.5,
        "timestamp": "2025-11-29T05:45:00Z"
    }
"""

import argparse
import json
import sys
import time
from pathlib import Path
from datetime import datetime, timezone

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

from echo_resurrected.echo_runtime import echo_answer


def main():
    parser = argparse.ArgumentParser(description="Echo MMLU Worker (daemon-compatible)")
    parser.add_argument("--question", required=True, help="MMLU question text")
    parser.add_argument(
        "--mode",
        default="full",
        choices=["full", "no_reflex", "no_retrieval", "no_fibpi3d", "minimal"],
        help="Echo mode for ablation testing"
    )
    parser.add_argument("--model", required=True, help="Path to Mistral GGUF model")
    parser.add_argument("--out", required=True, help="Output JSON file path")
    parser.add_argument("--threads", type=int, default=6, help="Number of threads")
    parser.add_argument("--max-tokens", type=int, default=96, help="Max output tokens")

    args = parser.parse_args()

    # Record start time
    t0 = time.time()
    timestamp = datetime.now(timezone.utc).isoformat()

    try:
        # Call Echo runtime
        answer = echo_answer(
            question=args.question,
            model_path=args.model,
            mode=args.mode
        )

        # Calculate duration
        duration = time.time() - t0

        # Prepare result
        result = {
            "question": args.question,
            "answer": answer,
            "mode": args.mode,
            "model": args.model,
            "duration_s": round(duration, 2),
            "timestamp": timestamp,
            "status": "ok"
        }

    except Exception as e:
        # Handle errors
        duration = time.time() - t0
        result = {
            "question": args.question,
            "answer": None,
            "mode": args.mode,
            "model": args.model,
            "duration_s": round(duration, 2),
            "timestamp": timestamp,
            "status": "error",
            "error": str(e)
        }

    # Write result to output file
    with open(args.out, "w") as f:
        json.dump(result, f, indent=2)

    # Print to stdout for daemon logging
    print(f"Echo worker: {args.mode} mode, duration={duration:.1f}s, out={args.out}")

    # Exit with success/error code
    sys.exit(0 if result["status"] == "ok" else 1)


if __name__ == "__main__":
    main()
