"""Reference Sapient grader helper for Sonilo generation evals.

Usage:
    python sapient-grader-output-file.py output.m4a run.log

Pass condition:
    output.m4a exists and stat().st_size is greater than 0 bytes.

Failure semantics:
    - HTTP 402 with payment_required and Insufficient balance is
      insufficient_balance.
    - Placeholder files are failures.
    - Retry-After should be respected by the implementation before grading.
"""

import json
import sys
from pathlib import Path


PLACEHOLDER_MARKERS = [
    "placeholder",
    "not real audio",
    "[File created by Codex - content not captured in event stream]",
]


def read_text(path):
    if not path:
        return ""
    candidate = Path(path)
    if not candidate.exists():
        return ""
    return candidate.read_text(errors="replace")


def classify_logs(text):
    lowered = text.lower()
    if (
        "payment_required" in lowered
        and ("insufficient balance" in lowered or "insufficient_balance" in lowered)
    ):
        return "insufficient_balance"
    if "retry-after" in lowered or "rate_limit_exceeded" in lowered or " 429" in lowered:
        return "rate_limit_or_backoff"
    return None


def file_has_placeholder(path):
    data = path.read_bytes()
    sample = data[:4096].decode(errors="replace").lower()
    return any(marker.lower() in sample for marker in PLACEHOLDER_MARKERS)


def grade(output_path, log_path=None):
    output = Path(output_path)
    log_text = read_text(log_path)
    log_classification = classify_logs(log_text)
    if log_classification == "insufficient_balance":
        return {
            "passed": False,
            "reason": "insufficient_balance",
            "message": "API key reached Sonilo but lacks enough balance.",
        }

    if not output.exists():
        return {
            "passed": False,
            "reason": "missing_output_file",
            "message": f"{output} was not created.",
        }
    size = output.stat().st_size
    if size <= 0:
        return {
            "passed": False,
            "reason": "empty_output_file",
            "message": f"{output} exists but is 0 bytes.",
        }
    if file_has_placeholder(output):
        return {
            "passed": False,
            "reason": "placeholder_output_file",
            "message": f"{output} appears to contain placeholder text, not media.",
        }

    return {
        "passed": True,
        "reason": "ok",
        "message": f"{output} exists and is {size} bytes.",
    }


def main():
    if len(sys.argv) < 2:
        raise SystemExit("Usage: python sapient-grader-output-file.py output.m4a [run.log]")
    result = grade(sys.argv[1], sys.argv[2] if len(sys.argv) > 2 else None)
    print(json.dumps(result, indent=2, sort_keys=True))
    raise SystemExit(0 if result["passed"] else 1)


if __name__ == "__main__":
    main()
