#!/opt/homebrew/bin/python3.11
"""Test ASR without Redis publisher."""

import subprocess
import tempfile
import os
import time
import sys


def test_no_redis():
    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,
            "--chunk-duration",
            "600",
        ]

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

        print(f"Running production ASR processor without UUID (no Redis publisher)...")
        print(f"Command: {' '.join(cmd)}")
        print(f"Env: ASR_DEBUG=1")
        print("-" * 60)

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

        timeout = 120  # 120 seconds
        killed = False
        stderr_lines = []
        stdout_lines = []

        from select import select

        while True:
            if proc.poll() is not None:
                remaining_stdout = proc.stdout.read()
                if remaining_stdout:
                    for line in remaining_stdout.split("\n"):
                        if line:
                            print(f"[stdout] {line}")
                            stdout_lines.append(line)
                remaining_stderr = proc.stderr.read()
                if remaining_stderr:
                    for line in remaining_stderr.split("\n"):
                        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

            readable, _, _ = select([proc.stdout, proc.stderr], [], [], 0.1)
            for stream in readable:
                if stream == proc.stdout:
                    line = proc.stdout.readline()
                    if line:
                        line = line.rstrip("\n")
                        print(f"[stdout] {line}")
                        stdout_lines.append(line)
                elif stream == proc.stderr:
                    line = proc.stderr.readline()
                    if line:
                        line = line.rstrip("\n")
                        print(f"[stderr] {line}")
                        stderr_lines.append(line)
            if not readable:
                time.sleep(0.05)

        if killed:
            proc.wait()

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

        if not killed and proc.returncode == 0:
            print(f"✓ Process completed successfully")
            if os.path.exists(output_path):
                import json

                with open(output_path, "r") as f:
                    data = json.load(f)
                print(f"  Segments: {len(data.get('segments', []))}")
                print(f"  Language: {data.get('language')}")
        else:
            print(f"✗ Process failed or killed")
            print(f"Last 20 lines of stderr:")
            for line in stderr_lines[-20:]:
                print(f"  {line}")
            print(f"Last 20 lines of stdout:")
            for line in stdout_lines[-20:]:
                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_no_redis()
