# Copyright (c) 2025 Airbyte, Inc., all rights reserved.
"""CLI commands for internal team roster operations.

Commands:
    airbyte-ops roster generate - Generate roster artifact from Slack and GitHub APIs
    airbyte-ops roster summary  - Print a matching summary from a roster JSON artifact

## CLI reference

The commands below are regenerated by `poe docs-generate` via cyclopts's
programmatic docs API; see `docs/generate_cli.py`.

.. include:: ../../../docs/generated/cli/roster.md
   :start-line: 2
"""

from __future__ import annotations

# Hide Python-level members from the pdoc page for this module; the rendered
# docs for this CLI group come entirely from the grafted `.. include::` in
# the module docstring above.
__all__: list[str] = []

import os
from pathlib import Path
from typing import Annotated

from cyclopts import Parameter

from airbyte_ops_mcp.cli._base import App, app
from airbyte_ops_mcp.cli._shared import console, exit_with_error, print_success
from airbyte_ops_mcp.github_api import resolve_default_github_token
from airbyte_ops_mcp.internal_team_roster import (
    generate_roster_to_file,
    summarize_roster,
)

# Create the roster sub-app
roster_app = App(name="roster", help="Internal team roster operations.")
app.command(roster_app)


@roster_app.command(name="generate")
def roster_generate(
    output: Annotated[
        str,
        Parameter(help="Output file path for the roster JSON artifact."),
    ],
) -> None:
    """Generate the internal team roster from Slack and GitHub APIs.

    Requires SLACK_HYDRA_BOT_TOKEN (or SLACK_AIRBYTE_TEAM_READ_USERS) and
    GITHUB_TOKEN environment variables.
    """
    slack_token = os.environ.get("SLACK_HYDRA_BOT_TOKEN") or os.environ.get(
        "SLACK_AIRBYTE_TEAM_READ_USERS",
    )
    if not slack_token:
        exit_with_error(
            "SLACK_HYDRA_BOT_TOKEN or SLACK_AIRBYTE_TEAM_READ_USERS "
            "environment variable is required."
        )

    github_token = os.environ.get("GITHUB_TOKEN")
    if not github_token:
        github_token = resolve_default_github_token()

    count = generate_roster_to_file(
        output_path=Path(output),
        slack_token=slack_token,
        github_token=github_token,
    )
    print_success(f"Roster generated: {count} members written to {output}")


@roster_app.command(name="summary")
def roster_summary(
    input: Annotated[
        str,
        Parameter(
            help="Path to a roster JSON file (produced by the generate command)."
        ),
    ],
) -> None:
    """Print a matching summary from a roster JSON artifact.

    Categorises roster members into matched, Slack-only, and GitHub-only
    groups and prints unmatched members for review.
    """
    path = Path(input)
    if not path.exists():
        exit_with_error(f"Roster file not found: {input}")

    text = summarize_roster(path)
    console.print(text)
