"""Basic conversion examples using the Melogen SDK."""

import os

from melogenai import Melogen, AuthenticationError, TaskTimeoutError


def main():
    api_key = os.getenv("MELOGEN_API_KEY")
    if not api_key:
        print("Set MELOGEN_API_KEY environment variable first")
        return

    client = Melogen(api_key=api_key)

    # --- Sheet music to MIDI ---
    print("Converting sheet music to MIDI...")
    try:
        result = client.sheet2midi.convert(
            file_url="https://example.com/score.pdf",
            output_formats=["midi", "musicxml"],
        )
        print(f"Task created: {result.task_id}")

        final = client.sheet2midi.wait(result.task_id)
        print(f"Status: {final.status}")
        for name, url in final.download_urls.items():
            print(f"  {name}: {url}")
    except AuthenticationError:
        print("Invalid API key")
    except TaskTimeoutError:
        print("Task timed out")

    # --- Audio to MIDI ---
    print("\nConverting audio to MIDI...")
    try:
        result = client.music2midi.convert(
            file_url="https://example.com/song.mp3",
            save_stems=True,
            quantize=True,
        )
        print(f"Task created: {result.task_id}")

        final = client.music2midi.wait(result.task_id)
        print(f"Status: {final.status}")
        for name, url in final.download_urls.items():
            print(f"  {name}: {url}")
    except AuthenticationError:
        print("Invalid API key")
    except TaskTimeoutError:
        print("Task timed out")

    # --- Music analysis (streaming) ---
    print("\nAnalyzing music structure...")
    try:
        for chunk in client.analysis.analyze_stream(
            image_url="https://example.com/score.png",
            language="en",
        ):
            print(chunk, end="", flush=True)
        print()
    except AuthenticationError:
        print("Invalid API key")


if __name__ == "__main__":
    main()
