from __future__ import annotations

import argparse
import sys
import webbrowser
from typing import Optional, Sequence
from urllib.parse import urlparse


def normalize_url(value: str) -> str:
    value = value.strip()
    if not value:
        raise ValueError("URL cannot be empty.")

    parsed = urlparse(value)
    if parsed.scheme:
        return value
    return f"https://{value}"


def build_parser() -> argparse.ArgumentParser:
    parser = argparse.ArgumentParser(
        prog="r",
        description="Open a URL in the default browser.",
    )
    parser.add_argument("url", help="The URL to open.")
    return parser


def main(argv: Optional[Sequence[str]] = None) -> int:
    parser = build_parser()
    args = parser.parse_args(argv)

    try:
        url = normalize_url(args.url)
    except ValueError as exc:
        print(str(exc), file=sys.stderr)
        return 2

    opened = webbrowser.open(url, new=2)
    if not opened:
        print(f"Failed to open URL: {url}", file=sys.stderr)
        return 1
    return 0