"""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 — write this as .gjalla/.commit-attestation.md
#
# The pre-commit hook validates this file before allowing a commit.
# The post-commit hook saves it to .gjalla/attestations/<hash>.yaml.
#
# 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)
#      and architecture via get_architecture_spec.
#   4. Fill in ALL fields below and save as .gjalla/.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.
#
# CLI shortcut (for simple attestations without full architecture detail):
#   gjalla attest --staged-diff-hash <hash> --agent <name> \
#     --provider <provider> --model <model> --summary "..."

# 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"

capabilities:
  changed: false

# 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
if [ "${SKIP_ATTESTATION:-0}" = "1" ]; then
  echo "[gjalla] Attestation skipped (SKIP_ATTESTATION=1)" >&2
  if command -v git &>/dev/null; then
    SKIP_BRANCH=$(git rev-parse --abbrev-ref HEAD 2>/dev/null || echo "unknown")
    mkdir -p .gjalla/attestations
    echo "{\"event\":\"attestation_skipped\",\"branch\":\"${SKIP_BRANCH}\",\"timestamp\":\"$(date -u +%Y-%m-%dT%H:%M:%SZ)\",\"synced\":false}" >> .gjallalog
  fi
  exit 0
fi

# 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=".gjalla/.commit-attestation.md"
if [ ! -f "$ATTESTATION" ]; then
  DIFF_HASH=$(git diff --staged | { shasum -a 256 2>/dev/null || sha256sum 2>/dev/null; } | cut -d' ' -f1)
  IS_AGENT=0
  if [ -n "${CLAUDE_CODE:-}" ] || [ -n "${CURSOR_SESSION_ID:-}" ] || [ -n "${AIDER_MODEL:-}" ] || [ -n "${CODEX_ENV:-}" ] || [ -n "${GEMINI_CLI:-}" ]; then
    IS_AGENT=1
  fi

  echo "━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━"
  echo "  gjalla: Attestation Required"
  echo "━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━"
  echo ""
  if [ "$IS_AGENT" = "1" ]; then
    echo "  YOU must create .gjalla/.commit-attestation.md before committing."
    echo ""
    echo "  1. Use the example at .gjalla/example-attestation.md for the format"
    echo "  2. Set staged_diff_hash to: $DIFF_HASH"
    echo "  3. Fetch rules (get_project_rules) and architecture (get_architecture_spec)"
    echo "  4. Fill in ALL architecture primitives (elements, connections, decisions,"
    echo "     data_flows, tech_stack, external_dependencies, services, capabilities)"
    echo "  5. Write the file, then retry git commit"
  else
    echo "  staged_diff_hash: $DIFF_HASH"
    echo ""
    echo "  Create .gjalla/.commit-attestation.md using the format in"
    echo "  .gjalla/example-attestation.md, or use the CLI shortcut:"
    echo "    gjalla attest --staged-diff-hash <hash> --agent <name> \\"
    echo "      --provider <provider> --model <model> --summary \"...\""
    echo ""
    # Only show skip hint to humans (interactive terminal)
    if [ -t 0 ]; then
      echo "  Human? Skip: SKIP_ATTESTATION=1 git commit ..."
    fi
  fi
  echo ""
  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 — always save attestation locally, then attempt upload.
ATTESTATION=".gjalla/.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 "")

# Always save full attestation locally
mkdir -p .gjalla/attestations
cp "$ATTESTATION" ".gjalla/attestations/${COMMIT}.yaml"

# Attempt upload if CLI is available
SYNCED=false
if command -v gjalla &>/dev/null; then
  if gjalla sync --up 2>/dev/null; then
    SYNCED=true
    echo "[gjalla] Attestation saved and uploaded."
  else
    echo "[gjalla] Attestation saved locally. Upload failed — run 'gjalla sync' later."
  fi
else
  echo "[gjalla] Attestation saved locally. Install CLI for auto-upload: pipx install gjalla"
fi

# Always log to .gjallalog
json_escape() { python3 -c "import sys,json; print(json.dumps(sys.argv[1]))" "$1" 2>/dev/null || printf '"%s"' "$(printf '%s' "$1" | sed 's/\\/\\\\/g;s/"/\\"/g')"; }
echo "{\"commit\":$(json_escape "$COMMIT"),\"branch\":$(json_escape "$BRANCH"),\"timestamp\":$(json_escape "$TIMESTAMP"),\"agent\":$(json_escape "$AGENT"),\"summary\":$(json_escape "$SUMMARY"),\"synced\":${SYNCED}}" >> .gjallalog

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