#!/usr/bin/env python3
"""
Speech recognition transcription script using the AI Builder Space API.
Transcribes voice memos in the memos/ folder and saves transcripts to transcripts/.
"""

import os
import sys
import time
from pathlib import Path
import requests

API_URL = "https://space.ai-builders.com/backend/v1/audio/grok-transcription"
SUPPORTED_EXTENSIONS = {".wav", ".mp3", ".m4a", ".ogg", ".flac", ".aac", ".webm", ".mp4", ".mkv"}


def get_api_key() -> str:
    """Retrieve API key from the environment variable AI_BUILDER_TOKEN."""
    api_key = os.environ.get("AI_BUILDER_TOKEN")
    if not api_key:
        print("Error: AI_BUILDER_TOKEN environment variable is not set.", file=sys.stderr)
        sys.exit(1)
    return api_key


def transcribe_file(file_path: Path, api_key: str, max_retries: int = 3) -> str:
    """Transcribe a single audio file with retry logic."""
    headers = {
        "Authorization": f"Bearer {api_key}"
    }

    for attempt in range(1, max_retries + 1):
        try:
            with open(file_path, "rb") as f:
                files = {"audio_file": (file_path.name, f)}
                data = {"simple": "true"}
                response = requests.post(API_URL, headers=headers, files=files, data=data, timeout=60)

            if response.status_code == 200:
                result = response.json()
                text = result.get("text", "")
                return text
            else:
                print(
                    f"Warning: Attempt {attempt} failed for {file_path.name} with HTTP {response.status_code}: {response.text}",
                    file=sys.stderr,
                )
        except Exception as e:
            print(f"Warning: Attempt {attempt} failed for {file_path.name}: {e}", file=sys.stderr)

        if attempt < max_retries:
            time.sleep(2 * attempt)

    raise RuntimeError(f"Failed to transcribe {file_path.name} after {max_retries} attempts.")


def main():
    api_key = get_api_key()

    base_dir = Path(__file__).resolve().parent
    memos_dir = base_dir / "memos"
    transcripts_dir = base_dir / "transcripts"

    if not memos_dir.is_dir():
        print(f"Error: memos directory not found at {memos_dir}", file=sys.stderr)
        sys.exit(1)

    transcripts_dir.mkdir(parents=True, exist_ok=True)

    memo_files = sorted(
        [p for p in memos_dir.iterdir() if p.is_file() and p.suffix.lower() in SUPPORTED_EXTENSIONS]
    )

    if not memo_files:
        print("No audio files found in memos/ directory.")
        return

    print(f"Found {len(memo_files)} audio file(s) in {memos_dir.name}/")

    for file_path in memo_files:
        output_file = transcripts_dir / f"{file_path.stem}.txt"
        print(f"Transcribing {file_path.name}...")

        transcript_text = transcribe_file(file_path, api_key)

        with open(output_file, "w", encoding="utf-8") as out:
            out.write(transcript_text)

        print(f"Saved transcript to {output_file.relative_to(base_dir)}")

    print("Transcription complete!")


if __name__ == "__main__":
    main()
