import os
import sys
from pathlib import Path
import requests

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


def transcribe_file(file_path: Path, token: str) -> str:
    """Transcribe a single audio file using the AI Builder Space API."""
    headers = {
        "Authorization": f"Bearer {token}",
    }
    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)

    if response.status_code != 200:
        raise RuntimeError(f"Transcription failed for {file_path.name} (HTTP {response.status_code}): {response.text}")

    result = response.json()
    return result.get("text", "")


def main():
    token = os.environ.get("AI_BUILDER_TOKEN")
    if not token:
        print("Error: AI_BUILDER_TOKEN environment variable not set.", file=sys.stderr)
        sys.exit(1)

    workspace_dir = Path.cwd()
    memos_dir = workspace_dir / "memos"
    transcripts_dir = workspace_dir / "transcripts"

    if not memos_dir.exists() or 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 and not p.name.startswith(".")
        ]
    )

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

    print(f"Found {len(memo_files)} memo(s) to transcribe.")

    for memo_path in memo_files:
        output_path = transcripts_dir / f"{memo_path.stem}.txt"
        print(f"Transcribing {memo_path.name}...")
        try:
            transcript = transcribe_file(memo_path, token)
            with open(output_path, "w", encoding="utf-8") as out:
                out.write(transcript)
            print(f"Saved transcript to {output_path.name}")
        except Exception as e:
            print(f"Error transcribing {memo_path.name}: {e}", file=sys.stderr)
            raise


if __name__ == "__main__":
    main()
