#!/usr/bin/env python3
"""Publish the single generated Android App Bundle as an action output."""

from __future__ import annotations

import os
from pathlib import Path

from android_config import ConfigError, detect_bundle


def gradle_module_dir() -> Path | None:
    """The Gradle application module's directory, when this is a native build."""
    root = os.environ.get("ANDROID_GRADLE_ROOT", "")
    module = os.environ.get("ANDROID_GRADLE_MODULE", "")
    if not root or not module:
        return None
    return Path(root) / module.lstrip(":").replace(":", "/") / "build"


def main() -> None:
    workspace = Path(os.environ.get("GITHUB_WORKSPACE", ".")).resolve()
    try:
        bundle = detect_bundle(workspace, gradle_module_dir()).resolve()
    except ConfigError as exc:
        print(f"::error::{exc}")
        raise SystemExit(1) from exc
    with Path(os.environ["GITHUB_OUTPUT"]).open("a") as stream:
        stream.write(f"bundle_path={bundle}\n")
    print(f"Built Android App Bundle: {bundle}")


if __name__ == "__main__":
    main()
