import base64
import webbrowser
import zlib

import click


def abc_url(s: str) -> str:
    compressed = base64.b64encode(zlib.compress(s.encode())).decode()
    return "https://abcviewer.sven.zone/?abc=" + (
        compressed.replace("+", "-").replace("/", "_").rstrip("=")
    )


@click.command()
@click.argument("file", type=click.Path(exists=True, dir_okay=False))
@click.option("--url", "url_only", is_flag=True, help="Print URL instead of opening browser")
def command(file, url_only):
    """View an ABC or MusicXML file in the browser.

    Supports .abc and .musicxml/.xml files. The viewer auto-detects the format:
    ABC is parsed natively; MusicXML is detected by <?xml / <score-partwise /
    <score-timewise and rendered as SVG via OpenSheetMusicDisplay.
    """
    with open(file, encoding="utf-8") as f:
        content = f.read()
    url = abc_url(content)
    if url_only:
        click.echo(url)
    else:
        click.echo(url)
        webbrowser.open(url)
