"""Validate GitHub Actions workflows that run anthropics/claude-code-action, then install the kit.

What you'll learn
  - The v1 shape of the action: `uses: anthropics/claude-code-action@v1`, a credential from
    `${{ secrets.* }}`, CLI flags in `claude_args`, and the mode it infers: no `prompt` input means
    interactive mode (waits for `@claude`), a `prompt` means automation mode.
  - What changed from @beta: `mode` is gone, `direct_prompt` became `prompt`, and `max_turns`, `model`,
    `allowed_tools` and friends moved into `claude_args`.
  - The security checks that matter on a workflow that can push code: minimal `permissions`
    (plus `id-token: write` for the default GitHub App auth), never a literal key, never
    `--dangerously-skip-permissions`, no PR-head checkout at the workspace root under
    `pull_request_target`, and care with `allowed_bots: "*"`, `allowed_non_write_users`, `show_full_output`.
  - The cost controls the docs recommend: `--max-turns` in `claude_args`, a job `timeout-minutes`,
    and `concurrency` to limit parallel runs.

How to run (from labs/)
  python3 core-4/gha_check.py                                  # check the kit (must be clean) and the bad sample
  python3 core-4/gha_check.py --path ~/code/my-app/.github/workflows/claude.yml   # check your own workflow files
  python3 core-4/gha_check.py --path my.yml --strict           # exit 1 if any error (for CI)
  Install the kit: mkdir -p <repo>/.github/workflows && cp core-4/kit/.github/workflows/claude.yml <repo>/.github/workflows/
  No network: the action's input list is a snapshot of its action.yml taken on 2026-10-20.

What to observe
  - The kit passes every check; the bad sample fails most of them, each finding with the doc that says why.
  - G009 on the bad sample: `pull_request_target` runs with the base repo's secrets, and the workflow
    checks out the PR head into the workspace root before the action runs.
  - G003 catches `sticky_comment`, a typo for `use_sticky_comment` that GitHub would only warn about.

Exercises
  1. Delete the `if:` from the kit's claude.yml and rerun. Which check fires, and what does the runner
     do on every comment without it?
  2. Change the kit's review workflow to the docs' "Run on a schedule" example (cron + a plain-text
     prompt and no --allowedTools). What does G007 tell you about the tools Claude gets?
  3. Fix bad-claude.yml one finding at a time until it passes. Which fixes change behavior, not just style?
  4. Pin the action to a full commit SHA instead of @v1. Which check notices, and what's the trade-off?

Docs: https://code.claude.com/docs/en/github-actions ; https://github.com/anthropics/claude-code-action/blob/main/action.yml ;
https://github.com/anthropics/claude-code-action/blob/main/docs/migration-guide.md ;
https://github.com/anthropics/claude-code-action/blob/main/docs/security.md
"""
from __future__ import annotations

import argparse
import re
import shlex
import sys
from dataclasses import dataclass
from pathlib import Path
from typing import Any, Dict, List, Optional, Sequence, Tuple

sys.dont_write_bytecode = True  # keep __pycache__ out of the lab folders
HERE = Path(__file__).resolve().parent
LABS = HERE.parent
sys.path.insert(0, str(LABS))
sys.path.insert(0, str(LABS / "core-1"))
import _yamlish  # noqa: E402
from common.pretty import c, header, kv, step, table  # noqa: E402

DOCS = "https://code.claude.com/docs/en/github-actions"
ACTION_YML = "https://github.com/anthropics/claude-code-action/blob/main/action.yml"
MIGRATION = "https://github.com/anthropics/claude-code-action/blob/main/docs/migration-guide.md"
SECURITY = "https://github.com/anthropics/claude-code-action/blob/main/docs/security.md"
ACTION = "anthropics/claude-code-action"
KIT = HERE / "kit" / ".github" / "workflows"
BAD_SAMPLE = HERE / "samples" / "workflows" / "bad-claude.yml"

# Input names from the action's action.yml, snapshot 2026-10-20 (39 inputs).
ACTION_INPUTS = frozenset((
    "additional_permissions", "allowed_bots", "allowed_non_write_users", "anthropic_api_key",
    "anthropic_federation_rule_id", "anthropic_oidc_audience", "anthropic_organization_id",
    "anthropic_service_account_id", "anthropic_workspace_id", "assignee_trigger", "base_branch", "bot_id", "bot_name",
    "branch_name_template", "branch_prefix", "classify_inline_comments", "claude_args", "claude_code_oauth_token",
    "display_report", "exclude_comments_by_actor", "github_token", "include_comments_by_actor", "include_fix_links",
    "label_trigger", "path_to_bun_executable", "path_to_claude_code_executable", "plugin_marketplaces", "plugins",
    "prompt", "settings", "show_full_output", "ssh_signing_key", "track_progress", "trigger_phrase", "use_bedrock",
    "use_commit_signing", "use_foundry", "use_sticky_comment", "use_vertex",
))
# Deprecated inputs -> replacement, from the migration guide's table (and the docs' "Upgrade from beta").
DEPRECATED = {
    "mode": "nothing: the action detects interactive vs automation mode itself",
    "direct_prompt": "prompt", "override_prompt": "prompt (use GitHub context variables)",
    "custom_instructions": "claude_args: --append-system-prompt", "max_turns": "claude_args: --max-turns",
    "model": "claude_args: --model", "allowed_tools": "claude_args: --allowedTools",
    "disallowed_tools": "claude_args: --disallowedTools", "claude_env": "settings with an env object",
    "mcp_config": "claude_args: --mcp-config", "timeout_minutes": "the job's timeout-minutes",
}
SECRET_INPUTS = ("anthropic_api_key", "claude_code_oauth_token", "github_token", "ssh_signing_key")
PROVIDER_INPUTS = ("use_bedrock", "use_vertex", "use_foundry")
INTERACTIVE_EVENTS = ("issue_comment", "pull_request_review_comment", "pull_request_review", "issues")
BYPASS_FLAGS = ("--dangerously-skip-permissions", "--allow-dangerously-skip-permissions")
SECRET_REF = re.compile(r"^\$\{\{\s*secrets\.[A-Za-z_][A-Za-z0-9_]*\s*\}\}$")


@dataclass
class Finding:
    code: str
    level: str      # error | warn | info
    where: str
    message: str
    ref: str        # the doc that says why


def _truthy(v: Any) -> bool:
    return str(v).strip().lower() == "true"


def _events(doc: Dict[str, Any]) -> List[str]:
    on = doc.get("on", doc.get(True))  # a YAML 1.1 parser would read `on:` as True
    if isinstance(on, str):
        return [on]
    if isinstance(on, list):
        return [str(x) for x in on]
    if isinstance(on, dict):
        return [str(k) for k in on]
    return []


def _claude_args(raw: Any) -> List[str]:
    if raw is None:
        return []
    try:
        return shlex.split(str(raw), comments=True)
    except ValueError:
        return str(raw).split()


def _flag_value(argv: Sequence[str], flag: str) -> Optional[str]:
    for i, a in enumerate(argv):
        if a == flag and i + 1 < len(argv):
            return argv[i + 1]
        if a.startswith(flag + "="):
            return a.split("=", 1)[1]
    return None


def check_workflow(path: Path) -> Tuple[List[Finding], int]:
    """Findings for one workflow file, and how many claude-code-action steps it has."""
    out: List[Finding] = []
    try:
        text = path.read_text(encoding="utf-8")
    except (OSError, UnicodeDecodeError) as e:
        return [Finding("G000", "error", path.name, f"can't read the file: {e}", DOCS)], 0
    try:
        doc = _yamlish.parse(text)
    except _yamlish.YamlError as e:
        return [Finding("G000", "error", path.name, f"YAML this checker can't parse: {e}", DOCS)], 0
    if not isinstance(doc, dict) or not isinstance(doc.get("jobs"), dict):
        return [Finding("G000", "error", path.name, "not a workflow: no `jobs:` mapping", DOCS)], 0
    events = _events(doc)
    wf_perms = doc.get("permissions")
    n_steps = 0
    for job_id, job in doc["jobs"].items():
        if not isinstance(job, dict):
            continue
        steps = job.get("steps") or []
        idx = [i for i, s in enumerate(steps) if isinstance(s, dict) and str(s.get("uses", "")).startswith(ACTION)]
        if not idx:
            continue
        n_steps += len(idx)
        perms = job.get("permissions", wf_perms)
        for i in idx:
            s = steps[i]
            where = f"jobs.{job_id}.steps[{i}]"
            w = s.get("with") or {}
            if not isinstance(w, dict):
                w = {}
            uses = str(s["uses"])
            ref = uses.split("@", 1)[1] if "@" in uses else ""

            # G001 version pin
            if ref == "beta":
                out.append(Finding("G001", "error", where, f"{uses}: @beta is the pre-v1 interface; use @v1", DOCS + "#upgrade-from-beta"))
            elif not ref:
                out.append(Finding("G001", "error", where, f"{uses} has no version; use @v1", DOCS))
            elif ref in ("main", "master"):
                out.append(Finding("G001", "warn", where, f"@{ref} follows the branch tip; pin @v1 or a commit SHA", DOCS))
            elif re.fullmatch(r"[0-9a-f]{40}", ref):
                out.append(Finding("G001", "info", where, "pinned to a commit SHA: reproducible, but update it yourself", DOCS))

            # G002 deprecated inputs, G003 unknown inputs
            for k in w:
                if k in DEPRECATED:
                    out.append(Finding("G002", "error", where, f"`{k}` was removed in v1; use {DEPRECATED[k]}", MIGRATION))
                elif k not in ACTION_INPUTS:
                    close = [x for x in ACTION_INPUTS if k in x or x in k]
                    hint = f" (did you mean {', '.join(sorted(close))}?)" if close else ""
                    out.append(Finding("G003", "warn", where, f"`{k}` isn't an input of the action{hint}", ACTION_YML))

            # G004 credentials
            for k in SECRET_INPUTS:
                if k in w and w[k] is not None and not SECRET_REF.match(str(w[k]).strip()):
                    out.append(Finding("G004", "error", where, f"`{k}` is a literal value; store it as a GitHub secret "
                                                               f"and pass ${{{{ secrets.NAME }}}}", SECURITY))
            federation = "anthropic_federation_rule_id" in w and "anthropic_organization_id" in w
            provider = any(_truthy(w.get(p)) for p in PROVIDER_INPUTS)
            if not ({"anthropic_api_key", "claude_code_oauth_token"} & set(w)) and not federation and not provider:
                out.append(Finding("G004", "error", where, "no credential: set anthropic_api_key or claude_code_oauth_token, "
                                                           "workload identity federation, or use_bedrock/use_vertex/use_foundry", DOCS))

            # G005 permissions
            pwhere = f"jobs.{job_id}.permissions"
            if perms is None:
                out.append(Finding("G005", "warn", pwhere, "no permissions block: the token gets the repository default; "
                                                           "grant only what the job needs", DOCS + "#protect-your-credentials"))
            elif perms in ("write-all", "read-all"):
                out.append(Finding("G005", "warn" if perms == "read-all" else "error", pwhere,
                                   f"permissions: {perms}; list the scopes the job needs instead", DOCS))
            elif isinstance(perms, dict):
                needs_oidc = federation or provider or "github_token" not in w
                if needs_oidc and perms.get("id-token") != "write":
                    out.append(Finding("G005", "warn", pwhere, "missing `id-token: write`: the default GitHub App "
                                                               "authentication (and OIDC providers) need it", DOCS + "#respond-to-claude-mentions"))
            # Mode: no prompt input = interactive (waits for the trigger phrase); a prompt = automation.
            # A beta-era direct_prompt/override_prompt also meant "run this prompt", so count it here.
            prompt = str(w.get("prompt") or w.get("direct_prompt") or w.get("override_prompt") or "").strip()
            interactive = not prompt
            if interactive and isinstance(perms, dict):
                ro = [k for k in ("contents", "pull-requests", "issues") if perms.get(k) != "write"]
                if ro:
                    out.append(Finding("G005", "info", pwhere, f"interactive mode with {', '.join(ro)} not `write`: "
                                                               "Claude can't push, open PRs or reply there", DOCS + "#manual-setup"))

            # G006 interactive mode: triggers and the job-level if
            if interactive:
                if not set(events) & set(INTERACTIVE_EVENTS):
                    out.append(Finding("G006", "warn", "on", "interactive mode (no prompt) but no comment, review or issue "
                                                             "trigger, so nobody can mention @claude", DOCS + "#interactive-and-automation-modes"))
                phrase = str(w.get("trigger_phrase") or "@claude")
                if phrase not in str(job.get("if", "")):
                    out.append(Finding("G006", "warn", f"jobs.{job_id}.if", f"no `if:` checking for {phrase!r}: a runner starts "
                                                                          "for every comment", DOCS + "#respond-to-claude-mentions"))

            # G007 automation mode: which tools does a plain-text prompt get?
            argv = _claude_args(w.get("claude_args"))
            allowed = _flag_value(argv, "--allowedTools") or _flag_value(argv, "--allowed-tools")
            if prompt and not prompt.startswith("/") and not allowed and "settings" not in w:
                out.append(Finding("G007", "info", where, "plain-text prompt with no --allowedTools or settings: Claude has "
                                                          "no shell or GitHub API access until you grant tools", DOCS + "#run-on-a-schedule"))

            # G008 claude_args
            for flag in BYPASS_FLAGS:
                if flag in argv:
                    out.append(Finding("G008", "error", where, f"{flag} in claude_args: never skip permission checks on a "
                                                               "runner that holds secrets and can push", DOCS))
            if _flag_value(argv, "--permission-mode") == "bypassPermissions":
                out.append(Finding("G008", "error", where, "--permission-mode bypassPermissions in claude_args", DOCS))
            if "--max-turns" not in " ".join(argv):
                out.append(Finding("G008", "warn", where, "no --max-turns in claude_args: cap iterations per run",
                                   DOCS + "#manage-costs"))
            if allowed:
                broad = [t for t in re.split(r"[,\s]+", allowed) if t in ("Bash", "Bash(*)", "Edit", "Write")]
                if "Bash" in broad or "Bash(*)" in broad:
                    out.append(Finding("G008", "warn", where, "--allowedTools grants all of Bash; list the commands the job "
                                                              "needs, e.g. Bash(npm test *)", "https://code.claude.com/docs/en/permissions"))

            # G009 untrusted checkout before the action under pull_request_target / workflow_run
            if {"pull_request_target", "workflow_run"} & set(events):
                for j, prev in enumerate(steps[:i]):
                    if not isinstance(prev, dict) or not str(prev.get("uses", "")).startswith("actions/checkout"):
                        continue
                    pw = prev.get("with") or {}
                    r = str(pw.get("ref", "")) if isinstance(pw, dict) else ""
                    if re.search(r"pull_request\.head|workflow_run\.head", r) and not (isinstance(pw, dict) and pw.get("path")):
                        out.append(Finding("G009", "error", f"jobs.{job_id}.steps[{j}]",
                                           "checks out the PR head into the workspace root before the action; check out "
                                           "the base ref, put the head in a subdirectory, pass --add-dir", SECURITY))
                out.append(Finding("G009", "warn", "on", "pull_request_target/workflow_run run with the base repository's "
                                                         "secrets; keep permissions minimal", SECURITY))

            # G010 who can trigger
            if str(w.get("allowed_bots", "")).strip() == "*":
                out.append(Finding("G010", "warn", where, "allowed_bots: '*' lets any bot trigger runs; on public repos "
                                                          "external Apps may invoke the action with prompts they control", ACTION_YML))
            if str(w.get("allowed_non_write_users", "")).strip():
                lvl = "error" if "github_token" not in w else "warn"
                out.append(Finding("G010", lvl, where, "allowed_non_write_users bypasses the write-access check (prompt "
                                                       "injection risk)" + ("; it only works with a github_token input"
                                                                            if lvl == "error" else ""), ACTION_YML))

            # G011 full output in public logs
            if _truthy(w.get("show_full_output")):
                out.append(Finding("G011", "warn", where, "show_full_output prints every message, including tool results "
                                                          "that may hold secrets, to the (possibly public) run log", SECURITY))

            # G013 skill prompts need their files
            if prompt.startswith("/"):
                name = prompt[1:].split()[0]
                checkout_before = any(isinstance(p, dict) and str(p.get("uses", "")).startswith("actions/checkout")
                                      for p in steps[:i])
                if ":" in name:
                    if not (w.get("plugins") and w.get("plugin_marketplaces")):
                        out.append(Finding("G013", "warn", where, f"prompt runs plugin skill /{name}: install it with "
                                                                  "plugins + plugin_marketplaces", DOCS + "#run-a-skill"))
                elif not checkout_before:
                    out.append(Finding("G013", "error", where, f"prompt runs repo skill /{name}, but no actions/checkout "
                                                               "runs first, so .claude/skills/ isn't on the runner", DOCS + "#run-a-skill"))
            elif interactive and not any(isinstance(p, dict) and str(p.get("uses", "")).startswith("actions/checkout")
                                         for p in steps[:i]):
                out.append(Finding("G013", "warn", where, "no actions/checkout before the action: Claude has no local copy "
                                                          "of the repository to work in", DOCS + "#respond-to-claude-mentions"))

        # G012 job-level cost controls
        if "timeout-minutes" not in job:
            out.append(Finding("G012", "warn", f"jobs.{job_id}", "no timeout-minutes: set a job timeout to stop runaway runs",
                               DOCS + "#manage-costs"))
        if "concurrency" not in job and "concurrency" not in doc:
            out.append(Finding("G012", "info", f"jobs.{job_id}", "no concurrency group: parallel runs on one PR can pile up",
                               DOCS + "#manage-costs"))
    if not n_steps:
        out.append(Finding("G000", "info", path.name, f"no step uses {ACTION}", DOCS))
    return out, n_steps


def report(path: Path, findings: List[Finding], n_steps: int) -> Tuple[int, int]:
    errors = sum(f.level == "error" for f in findings)
    warns = sum(f.level == "warn" for f in findings)
    try:
        shown = path.resolve().relative_to(LABS)
    except ValueError:
        shown = path
    status = c("clean", "green") if not errors and not warns else (c(f"{errors} error(s)", "red") + f", {warns} warning(s)")
    print(f"\n{c(str(shown), 'bold')}: {n_steps} claude-code-action step(s), {status}")
    if findings:
        rows = [[f.code, c(f.level, {"error": "red", "warn": "yellow", "info": "gray"}[f.level]), f.where, f.message]
                for f in sorted(findings, key=lambda f: (f.code, f.where))]
        table(rows, ["check", "level", "where", "finding"])
        refs = sorted({f.ref for f in findings})
        print(c("  why: " + " ; ".join(refs), "gray"))
    return errors, warns


def main() -> int:
    ap = argparse.ArgumentParser(description=__doc__.split("\n", 1)[0],
                                 formatter_class=argparse.RawDescriptionHelpFormatter)
    ap.add_argument("--path", nargs="+", type=Path, default=None, help="workflow file(s) to check instead of the kit + sample")
    ap.add_argument("--strict", action="store_true", help="exit 1 when any file has an error")
    args = ap.parse_args()
    if args.strict and not args.path:
        ap.error("--strict applies to the files you pass with --path (the default run expects the bad sample to fail)")
    if args.path:
        missing = [str(p) for p in args.path if not p.is_file()]
        if missing:
            ap.error(f"not a file: {', '.join(missing)}")
        header(f"claude-code-action workflow check · {len(args.path)} file(s)")
        total_err = 0
        for p in args.path:
            e, _ = report(p, *check_workflow(p))
            total_err += e
        return 1 if (args.strict and total_err) else 0

    header("claude-code-action workflow check · kit + bad sample")
    step(1, "The kit (core-4/kit/.github/workflows), which must pass")
    kit_files = sorted(KIT.glob("*.yml"))
    kit_bad = 0
    for p in kit_files:
        e, w = report(p, *check_workflow(p))
        kit_bad += e + w
    print()
    step(2, "A deliberately broken workflow (core-4/samples/workflows/bad-claude.yml)")
    bad_err, _ = report(BAD_SAMPLE, *check_workflow(BAD_SAMPLE))
    print()
    step(3, "Install the kit into your repo")
    print("  mkdir -p <repo>/.github/workflows && cp core-4/kit/.github/workflows/claude.yml <repo>/.github/workflows/")
    print("  # optional automatic PR review: also copy claude-review.yml")
    print("  Then install the Claude GitHub App (https://github.com/apps/claude) and add the repository secret")
    print("  ANTHROPIC_API_KEY (or CLAUDE_CODE_OAUTH_TOKEN from `claude setup-token`, and switch the input name).")
    print("  Or run /install-github-app in Claude Code to do all three (github.com only).")
    print("  Edit --allowedTools in claude_args to the commands your project needs before you commit it.")
    if kit_bad:
        print(c(f"\nThe kit has {kit_bad} finding(s); it should be clean.", "red"))
        return 1
    if not bad_err:
        print(c("\nThe bad sample produced no errors; the checker is broken.", "red"))
        return 1
    print(c(f"\nkit: {len(kit_files)} file(s) clean · bad sample: {bad_err} error(s)", "gray"))
    return 0


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