#!/usr/bin/env python3
"""Bitbucket Cloud REST API v2.0 wrapper.

Thin layer over http.py for Bitbucket-specific operations:

- Bearer token authentication
- Repository existence checks
- Repository creation within a workspace/project
"""

import json
from typing import Any, Dict, Optional

from byteb4rb1e.utils.http import client as http_client


BITBUCKET_API = "https://api.bitbucket.org/2.0"


def http_headers(token: str) -> Dict[str, str]:
    """Construct Bitbucket API headers with Bearer token auth."""
    return {
        "Authorization": f"Bearer {token}",
        "Accept": "application/json",
        "Content-Type": "application/json",
    }


def repository_exists(
    workspace: str,
    repo_slug: str,
    token: str,
) -> bool:
    """Check whether a repository exists in the workspace."""
    url = f"{BITBUCKET_API}/repositories/{workspace}/{repo_slug}"
    resp = http_client.get(url, headers=http_headers(token))
    return resp.status_code == 200


def create_repository(
    workspace: str,
    repo_slug: str,
    token: str,
    project: Optional[str] = None,
    description: str = "",
    is_private: bool = True,
) -> http_client.HttpResponse:
    """Create a new repository in the workspace.

    When *project* is given the repository is assigned to that
    Bitbucket project (by key).  This is required for workspaces
    that scope access keys at the project level.

    Returns the API response.  Caller should check status_code == 200
    for success.
    """
    url = f"{BITBUCKET_API}/repositories/{workspace}/{repo_slug}"
    body: Dict[str, Any] = {
        "scm": "git",
        "is_private": is_private,
        "description": description,
        "fork_policy": "no_forks",
    }
    if project:
        body["project"] = {"key": project}
    return http_client.put(
        url,
        data=json.dumps(body).encode("utf-8"),
        headers=http_headers(token),
    )


def clone_url(
    workspace: str,
    repo_slug: str,
) -> str:
    """Return the SSH clone URL for a Bitbucket repository."""
    return f"git@bitbucket.org:{workspace}/{repo_slug}.git"
