#!/usr/bin/env python3
"""
Resolve the App Store Connect numeric app id for a bundle id.

Environment:
    ASC_KEY_ID     - API key ID
    ASC_ISSUER_ID  - API issuer ID
    ASC_KEY_PATH   - Path to the .p8 key file
    BUNDLE_ID      - Application bundle identifier

Prints the app id to stdout on success. On 0 or >1 matches, exits 1 with a
guidance message on stderr.
"""

from __future__ import annotations

import os

from asc_common import get_json, make_jwt
from cfg_io import fail


def env(name: str) -> str:
    val = os.environ.get(name)
    if not val:
        fail(f"missing env var: {name}")
    return val


def main() -> None:
    bundle_id = env("BUNDLE_ID")
    token = make_jwt(env("ASC_KEY_ID"), env("ASC_ISSUER_ID"), env("ASC_KEY_PATH"))
    data = get_json("/apps", token, params={"filter[bundleId]": bundle_id, "limit": "10"})
    apps = data.get("data", [])
    if not apps:
        fail(
            f"No ASC app found for bundleId={bundle_id}. "
            "Run `fastlane create_app_ios` once manually to register the app, "
            "or set app.app_store_apple_id in ci.config.yaml."
        )
    if len(apps) > 1:
        ids = ", ".join(a.get("id", "?") for a in apps)
        fail(
            f"Multiple ASC apps match bundleId={bundle_id} (ids: {ids}). "
            "Set app.app_store_apple_id in ci.config.yaml to disambiguate."
        )
    print(apps[0]["id"])


if __name__ == "__main__":
    main()
