#!/usr/bin/env python3
"""Git credential helper for the two LSMC Bio headnode repositories.

The helper stores no GitHub credential locally.  Git invokes it on demand;
the helper reads the configured Secrets Manager reference and returns a token
only for the explicitly allowlisted HTTPS repository paths.
"""

from __future__ import annotations

import json
import os
import subprocess
import sys
from pathlib import Path
from typing import Mapping


CONFIG_PATH = Path.home() / ".config" / "daylily" / "github_token.json"
ALLOWED_REPOSITORIES = frozenset(
    {
        "lsmc-bio/daylily-ephemeral-cluster",
        "lsmc-bio/daylily-omics-analysis",
    }
)


class CredentialError(RuntimeError):
    """Raised when the managed headnode Git credential is invalid."""


def _read_request() -> dict[str, str]:
    values: dict[str, str] = {}
    for raw_line in sys.stdin:
        line = raw_line.rstrip("\n")
        if not line:
            break
        key, separator, value = line.partition("=")
        if separator:
            values[key] = value
    return values


def _normalized_repository(request: Mapping[str, str]) -> str:
    if request.get("protocol") != "https" or request.get("host") != "github.com":
        return ""
    path = request.get("path", "").strip().strip("/")
    if path.endswith(".git"):
        path = path[: -len(".git")]
    return path


def _load_config(path: Path | None = None) -> dict[str, str]:
    path = path or CONFIG_PATH
    try:
        mode = path.stat().st_mode & 0o777
    except OSError as exc:
        raise CredentialError(f"Missing managed GitHub token reference: {path}") from exc
    if mode & 0o077:
        raise CredentialError(f"Managed GitHub token reference must not be group/world-readable: {path}")
    try:
        payload = json.loads(path.read_text(encoding="utf-8"))
    except (OSError, json.JSONDecodeError) as exc:
        raise CredentialError(f"Invalid managed GitHub token reference: {path}") from exc
    if not isinstance(payload, dict) or payload.get("config_version") != 1:
        raise CredentialError(f"Unsupported managed GitHub token reference: {path}")
    secret_arn = str(payload.get("secret_arn") or "").strip()
    region = str(payload.get("region") or "").strip()
    if not secret_arn or not region:
        raise CredentialError("Managed GitHub token reference requires secret_arn and region.")
    return {"secret_arn": secret_arn, "region": region}


def _read_token(config: Mapping[str, str]) -> str:
    env = os.environ.copy()
    env["AWS_PAGER"] = ""
    result = subprocess.run(
        [
            "aws",
            "secretsmanager",
            "get-secret-value",
            "--region",
            config["region"],
            "--secret-id",
            config["secret_arn"],
            "--query",
            "SecretString",
            "--output",
            "text",
            "--no-cli-pager",
        ],
        check=False,
        capture_output=True,
        text=True,
        env=env,
    )
    if result.returncode != 0:
        detail = result.stderr.strip() or "Secrets Manager returned a non-zero status."
        raise CredentialError(f"Unable to read managed GitHub token: {detail}")
    token = result.stdout.strip()
    if not token or "\n" in token or "\r" in token:
        raise CredentialError("Managed GitHub token must be a single non-empty SecretString.")
    return token


def main() -> int:
    request = _read_request()
    operation = sys.argv[1] if len(sys.argv) > 1 and sys.argv[1] == "get" else request.get("operation", "")
    if operation != "get":
        return 0
    repository = _normalized_repository(request)
    if repository not in ALLOWED_REPOSITORIES:
        return 0
    try:
        token = _read_token(_load_config())
    except CredentialError as exc:
        print(f"daylily-github-credential: {exc}", file=sys.stderr)
        return 1
    print("username=x-access-token")
    print(f"password={token}")
    return 0


if __name__ == "__main__":
    raise SystemExit(main())
