"""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.
# 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 — which services/components does this change touch?
# Use names from the project architecture (get_architecture_spec).
services_affected:
  - "web-api"

# Optional — tech stack used in this change.
tech_stack_used:
  - "typescript"
  - "react"

# Optional — does this change modify the architecture (new services,
# new connections, changed boundaries)?
architecture:
  changes: false

# REQUIRED — one-line impact summary (not a commit message).
# Focus on WHAT CHANGED for the system, not what you did.
#   Good: "Auth endpoints now enforce rate limiting"
#   Bad:  "Added rate limiting middleware to auth endpoints"
summary: "Docs page now includes CLI setup guide for guardrails"
---
'''


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 "  1. Read the example format: .gjalla/example-attestation.md"
  echo "  2. Fetch project rules via gjalla MCP (get_project_rules)"
  echo "  3. Once you've verified that you adhere to them, create .commit-attestation.md (do NOT git add it)"
  echo "  4. Run git commit again"
  echo ""
  echo "  staged_diff_hash: $DIFF_HASH"
  echo ""
  echo "  Human? Skip: SKIP_ATTESTATION=1 git commit ..."
  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 log to .gjallalog, then attempt upload.
ATTESTATION=".commit-attestation.md"
[ ! -f "$ATTESTATION" ] && exit 0

# Extract fields from attestation
COMMIT=$(git rev-parse HEAD 2>/dev/null || echo "unknown")
BRANCH=$(git rev-parse --abbrev-ref HEAD 2>/dev/null || echo "unknown")
TS=$(grep -m1 'timestamp:' "$ATTESTATION" | sed "s/.*timestamp: *//" | tr -d "\"'")
AGENT=$(grep -m1 'agent:' "$ATTESTATION" | sed "s/.*agent: *//" | tr -d "\"'")
PROVIDER=$(grep -m1 'agent_provider:' "$ATTESTATION" | sed "s/.*agent_provider: *//" | tr -d "\"'")
MODEL=$(grep -m1 'agent_model:' "$ATTESTATION" | sed "s/.*agent_model: *//" | tr -d "\"'")
SUMMARY=$(grep -m1 'summary:' "$ATTESTATION" | sed "s/.*summary: *//" | tr -d "\"")

# Attempt upload via gjalla CLI
UPLOADED="false"
if command -v gjalla &>/dev/null; then
  if gjalla sync --up 2>/dev/null; then
    UPLOADED="true"
    echo "[gjalla] Attestation uploaded."
  else
    echo "[gjalla] Upload failed — logged locally for later sync."
  fi
else
  echo "[gjalla] CLI not found — logging attestation locally."
  echo "[gjalla] Install for auto-upload: pip install gjalla  (or: pipx install gjalla)"
fi

# Always append to .gjallalog
echo "{\"ts\":\"${TS}\",\"commit\":\"${COMMIT}\",\"branch\":\"${BRANCH}\",\"agent\":\"${AGENT}\",\"agent_provider\":\"${PROVIDER}\",\"agent_model\":\"${MODEL}\",\"summary\":\"${SUMMARY}\",\"uploaded\":${UPLOADED}}" >> .gjallalog

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