#!/opt/homebrew/bin/python3.11
"""Test production ASR processor with large video."""

import subprocess
import tempfile
import os
import time
import sys


def test_production():
    test_video = "/Users/accusys/test_video/1636719d-c31f-78ac-f1dd-8ab0b0b36c66.mov"
    if not os.path.exists(test_video):
        print(f"Test video not found: {test_video}")
        return

    with tempfile.NamedTemporaryFile(suffix=".json", delete=False) as f:
        output_path = f.name

    try:
        cmd = [
            "/opt/homebrew/bin/python3.11",
            "scripts/asr_processor.py",
            test_video,
            output_path,
            "--uuid",
            "test_production",
            "--chunk-duration",
            "60",
        ]

        env = os.environ.copy()
        env["MOMENTRY_DISABLE_REDIS"] = "1"

        print(f"Running production ASR processor...")
        print(f"Command: {' '.join(cmd)}")
        print(f"Env: MOMENTRY_DISABLE_REDIS=1")
        print("-" * 60)

        start = time.time()
        proc = subprocess.Popen(
            cmd,
            stdout=subprocess.PIPE,
            stderr=subprocess.PIPE,
            text=True,
            bufsize=1,
            env=env,
        )

        timeout = 30  # 30 seconds
        killed = False
        stderr_lines = []

        while True:
            if proc.poll() is not None:
                remaining_stderr = proc.stderr.read()
                if remaining_stderr:
                    lines = remaining_stderr.split("\n")
                    for line in lines:
                        if line:
                            print(f"[stderr] {line}")
                            stderr_lines.append(line)
                break

            if time.time() - start > timeout:
                print(f"\n⏱️ TIMEOUT after {timeout}s - killing process")
                proc.kill()
                killed = True
                break

            line = proc.stderr.readline()
            if line:
                line = line.rstrip("\n")
                print(f"[stderr] {line}")
                stderr_lines.append(line)
            else:
                time.sleep(0.1)

        if killed:
            proc.wait()

        elapsed = time.time() - start
        print(f"\n" + "=" * 60)
        print(
            f"Elapsed: {elapsed:.1f}s, Killed: {killed}, Return code: {proc.returncode}"
        )

        # Look for key phrases
        print("\nKey phrases in stderr:")
        phrases = ["ASR:", "DEBUG:", "ERROR:", "WARNING:", "transcribing", "chunk"]
        for line in stderr_lines:
            if any(phrase.lower() in line.lower() for phrase in phrases):
                print(f"  {line}")

    except Exception as e:
        print(f"✗ Error: {e}")
        import traceback

        traceback.print_exc()
    finally:
        if os.path.exists(output_path):
            os.unlink(output_path)
            print(f"✓ Cleaned up output file")


if __name__ == "__main__":
    test_production()
