"""ACR token and Apollo publish tools."""

from __future__ import annotations

import logging
import tempfile
from pathlib import Path

import httpx

from cube_common.apollo_client import ApolloClient
from cube_common.config import APOLLO_URL

logger = logging.getLogger(__name__)


async def acr_get_token(client: ApolloClient) -> str:
    """Get a raw ACR OAuth2 token. Returns the full token for agent use."""
    token = await client.get_token()
    return token


async def apollo_publish_manifest(client: ApolloClient, manifest_yaml: str) -> str:
    """Publish a manifest to Apollo using the Apollo REST API.

    Replaces the `apollo-cli publish manifest` command.
    Uses the Apollo product-release API to publish the manifest.
    """
    token = await client.get_token()

    # Apollo publish manifest API endpoint
    url = f"{APOLLO_URL}/product-release/api/publish"

    async with httpx.AsyncClient(timeout=60) as http:
        resp = await http.post(
            url,
            content=manifest_yaml.encode(),
            headers={
                "Authorization": f"Bearer {token}",
                "Content-Type": "application/x-yaml",
            },
        )

    if resp.status_code in (200, 201, 204):
        return "Manifest published to Apollo successfully."

    return f"Apollo publish failed ({resp.status_code}): {resp.text[:500]}"
