#!/usr/bin/env python3
import json
import subprocess
import os


def main():
    # Find latest ASR file for job 10
    output_dir = "/Users/accusys/momentry/output"
    files = [f for f in os.listdir(output_dir) if f.startswith("job_10_asr_")]
    if not files:
        print("No ASR files found")
        return

    # Sort by timestamp (numeric suffix)
    def extract_timestamp(fname):
        # job_10_asr_1774505428450.json
        parts = fname.split("_")
        timestamp = parts[3].split(".")[0]
        return int(timestamp)

    files.sort(key=extract_timestamp, reverse=True)
    latest_file = os.path.join(output_dir, files[0])
    print(f"Using ASR file: {latest_file}")

    with open(latest_file, "r") as f:
        data = json.load(f)

    # Convert to JSON string, escape single quotes for SQL
    json_str = json.dumps(data).replace("'", "''")

    # Update processor_results
    sql = f"""
    UPDATE processor_results 
    SET status = 'completed',
        output_data = '{json_str}'::jsonb,
        completed_at = NOW()
    WHERE job_id = 10 AND processor = 'asr';
    """

    # Execute with psql
    db_url = "postgres://accusys@localhost:5432/momentry"
    cmd = ["psql", db_url, "-c", sql]
    result = subprocess.run(cmd, capture_output=True, text=True)
    if result.returncode != 0:
        print(f"Error updating database: {result.stderr}")
    else:
        print("Successfully updated ASR processor result to completed")

    # Also need to store ASR chunks in database via Rust logic
    # For now, we'll trust that the worker will do it when restarted
    # (the store_asr_chunks method will be called on completion)


if __name__ == "__main__":
    main()
