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", ".opus", ".flac", ".mp4", ".mkv", ".webm"
}


def transcribe_audio(file_path: Path, token: str) -> str:
    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)
        response.raise_for_status()
        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 is not set.", file=sys.stderr)
        sys.exit(1)

    memos_dir = Path("memos")
    if not memos_dir.exists() or not memos_dir.is_dir():
        print(f"Error: Directory '{memos_dir}' not found.", file=sys.stderr)
        sys.exit(1)

    transcripts_dir = Path("transcripts")
    transcripts_dir.mkdir(parents=True, exist_ok=True)

    audio_files = sorted(
        [
            f for f in memos_dir.iterdir()
            if f.is_file() and not f.name.startswith(".") and f.suffix.lower() in SUPPORTED_EXTENSIONS
        ]
    )

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

    print(f"Found {len(audio_files)} audio file(s) to transcribe.")

    for audio_file in audio_files:
        print(f"Transcribing {audio_file.name}...")
        try:
            transcript_text = transcribe_audio(audio_file, token)
            output_file = transcripts_dir / f"{audio_file.stem}.txt"
            output_file.write_text(transcript_text.strip() + "\n", encoding="utf-8")
            print(f"Saved transcript to {output_file}")
        except Exception as e:
            print(f"Failed to transcribe {audio_file.name}: {e}", file=sys.stderr)
            raise


if __name__ == "__main__":
    main()
