"""Bash script templates and attestation examples for hooks."""


def example_attestation() -> str:
    """Return the example attestation file content.

    This is saved to .gjalla/example-attestation.md so agents have
    a concrete reference for the required format.
    """
    return '''---
# Gjalla Commit Attestation — create as .commit-attestation.md in the repo root.
#
# CLI shortcut (recommended):
#   gjalla attest \\
#     --staged-diff-hash $(git diff --staged | shasum -a 256 | cut -d' ' -f1) \\
#     --agent claude-code --provider anthropic --model claude-opus-4-6 \\
#     --summary "..." \\
#     --rules '{"checked": true, "applicable": [...]}' \\
#     --arch-changes '{"architecture_elements": {"changed": false}, ...}'
#
# The pre-commit hook validates this file before allowing a commit.
#
# How to fill this out:
#   1. Stage your changes (git add ...)
#   2. Compute the diff hash:  git diff --staged | shasum -a 256
#   3. Fetch project rules via the gjalla MCP server (get_project_rules)
#      or from the project rules URL shown in the pre-commit error.
#   4. Fill in each field below and save as .commit-attestation.md
#   5. Run git commit — the hook will verify the hash matches.
#
# IMPORTANT: Do NOT stage or commit this file. It is consumed by the
# post-commit hook and cleaned up automatically.

# REQUIRED — must match `git diff --staged | shasum -a 256` at commit time.
staged_diff_hash: "abc123..."

# REQUIRED — ISO 8601 timestamp of when this attestation was created.
timestamp: "2026-02-11T12:00:00Z"

# REQUIRED — the name of the coding agent (e.g. "claude-code", "cursor", "aider").
agent: "claude-code"

# REQUIRED — who provides the model (e.g. "anthropic", "openai", "google").
agent_provider: "anthropic"

# REQUIRED — the specific model used (e.g. "claude-opus-4-6", "gpt-4o").
agent_model: "claude-opus-4-6"

# REQUIRED — did you check the project rules before committing?
rules:
  checked: true
  # List each rule you reviewed. Use the rule names from get_project_rules.
  # Status should be "compliant", "not-applicable", or "needs-review".
  applicable:
    - id: "separation-of-concerns"
      status: "compliant"
    - id: "no-source-code-in-db"
      status: "not-applicable"

# REQUIRED — self-report changes to architecture primitives.
# Each primitive is a peer. Set changed: true/false for each.
# If true, include a details list describing what changed.
# Use names from the project architecture (get_architecture_spec).

architecture_elements:
  changed: true
  details:
    - modified: "web-api — added rate limiting middleware layer"

architecture_connections:
  changed: true
  details:
    - added: "web-api → redis — rate limit counters"

architecture_decisions:
  changed: true
  details:
    - "Use token-bucket rate limiting at the gateway, not per-service"

data_flows:
  changed: false

tech_stack:
  changed: false

external_dependencies:
  changed: true
  details:
    - added: "rate-limiter-flexible@^5.0.0"
    - updated: "express@4.18 → 4.19"

services:
  changed: true
  details:
    - added: "Redis (Upstash) — rate limit counter store"

# REQUIRED — one-line impact summary (not a commit message).
# Focus on the SO WHAT of the changes in this commit.
#   Good: "New rate limiting additions help protect the API from abuse"
#   Bad:  "Added rate limiting middleware to auth endpoints"
summary: "Auth endpoints now enforce token-bucket rate limiting"
---
'''


def attestation_pre_commit_script() -> str:
    """Return the attestation pre-commit check script."""
    return r'''#!/usr/bin/env bash
set -euo pipefail
# Gjalla Attestation Gate — agent-agnostic, no Python required

GJALLA_CONFIG=".gjalla/config.json"
# Support both new (.gjalla/config.json) and old (.gjalla file) formats
[ ! -f "$GJALLA_CONFIG" ] && GJALLA_CONFIG=".gjalla"
[ ! -f "$GJALLA_CONFIG" ] && exit 0
[ "${SKIP_ATTESTATION:-0}" = "1" ] && exit 0

# Soft check — inform if gjalla CLI is not installed (not blocking)
if ! command -v gjalla &>/dev/null; then
  echo "[gjalla] CLI not installed. Attestation uploads require it."
  echo "[gjalla] Install: pip install gjalla  (or: pipx install gjalla)"
fi

ATTESTATION=".commit-attestation.md"
if [ ! -f "$ATTESTATION" ]; then
  PROJECT_ID=$(python3 -c "import json; print(json.load(open('$GJALLA_CONFIG'))['project_id'])" 2>/dev/null || echo "unknown")
  API_URL=$(python3 -c "import json; print(json.load(open('$GJALLA_CONFIG'))['api_url'])" 2>/dev/null || echo "https://gjalla.io")
  DIFF_HASH=$(git diff --staged | { shasum -a 256 2>/dev/null || sha256sum 2>/dev/null; } | cut -d' ' -f1)
  echo "━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━"
  echo "  gjalla: Attestation Required"
  echo "━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━"
  echo ""
  echo "  staged_diff_hash: $DIFF_HASH"
  echo ""
  echo "  Create your attestation:"
  echo "    gjalla attest --staged-diff-hash <hash> --agent <name> \\"
  echo "      --provider <provider> --model <model> --summary \"...\""
  echo ""
  echo "  Run 'gjalla attest --help' for full options and"
  echo "  guidance on where to find rules and architecture context."
  echo ""
  # Only show skip hint to humans (interactive terminal, no known agent env vars)
  if [ -t 0 ] && [ -z "${CLAUDE_CODE:-}" ] && [ -z "${CURSOR_SESSION_ID:-}" ] && [ -z "${AIDER_MODEL:-}" ] && [ -z "${CODEX_ENV:-}" ]; then
    echo "  Human? Skip: SKIP_ATTESTATION=1 git commit ..."
  fi
  echo "━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━"
  exit 1
fi

# Validate diff hash
CURRENT=$(git diff --staged | { shasum -a 256 2>/dev/null || sha256sum 2>/dev/null; } | cut -d' ' -f1)
ATTESTED=$(grep -m1 'staged_diff_hash:' "$ATTESTATION" | sed 's/.*staged_diff_hash: *//' | tr -d "\"'")
if [ "$CURRENT" != "$ATTESTED" ]; then
  echo "[gjalla] Attestation stale — staged changes differ from attested hash"
  echo "  Expected: ${ATTESTED:0:16}..."
  echo "  Current:  ${CURRENT:0:16}..."
  exit 1
fi
echo "[gjalla] Attestation verified"
'''


def post_commit_upload_script() -> str:
    """Return the post-commit upload script."""
    return r'''#!/usr/bin/env bash
# Gjalla Post-Commit — save attestation to .gjalla/attestations/, log minimal entry, then attempt upload.
ATTESTATION=".commit-attestation.md"
[ ! -f "$ATTESTATION" ] && exit 0

COMMIT=$(git rev-parse HEAD 2>/dev/null || echo "unknown")
BRANCH=$(git rev-parse --abbrev-ref HEAD 2>/dev/null || echo "unknown")
TIMESTAMP=$(grep -m1 'timestamp:' "$ATTESTATION" | sed 's/.*timestamp: *//' | tr -d "\"'" 2>/dev/null || echo "")
AGENT=$(grep -m1 'agent:' "$ATTESTATION" | grep -v 'agent_' | sed 's/.*agent: *//' | tr -d "\"'" 2>/dev/null || echo "")
SUMMARY=$(grep -m1 'summary:' "$ATTESTATION" | sed 's/.*summary: *//' | tr -d "\"'" 2>/dev/null || echo "")

# Prefer gjalla CLI — it YAML-parses the full attestation
if command -v gjalla &>/dev/null; then
  if gjalla sync --up 2>/dev/null; then
    echo "[gjalla] Attestation logged and uploaded."
  else
    echo "[gjalla] Upload failed — attestation logged locally for later sync."
  fi
else
  # Fallback: save full attestation to .gjalla/attestations/ and minimal entry to .gjallalog
  mkdir -p .gjalla/attestations
  cp "$ATTESTATION" ".gjalla/attestations/${COMMIT}.yaml"
  echo "{\"commit\":\"${COMMIT}\",\"branch\":\"${BRANCH}\",\"timestamp\":\"${TIMESTAMP}\",\"agent\":\"${AGENT}\",\"summary\":\"${SUMMARY}\",\"synced\":false}" >> .gjallalog
  echo "[gjalla] CLI not found — attestation saved locally."
  echo "[gjalla] Install for auto-upload: pip install gjalla  (or: pipx install gjalla)"
fi

# Clean up attestation file
rm -f "$ATTESTATION"
exit 0
'''
