"""Template content for `ievo init` scaffolding."""

PRIORITY_MD = """\
# Priority Algorithm

## How the Coding Agent selects the next requirement

### Scoring Formula

```
score = (priority_weight x 10)
      + (dependency_satisfaction x 5)
      + (blocking_count x 3)
      - (complexity_penalty x 2)
      - (open_questions x 100)
```

### Variables

**priority_weight** (from requirement's Priority field):

| Priority | Weight |
|----------|--------|
| critical | 10 |
| high | 7 |
| medium | 4 |
| low | 1 |

**dependency_satisfaction:**

| State | Value |
|-------|-------|
| All dependencies are `implemented` | 10 |
| Some dependencies are `implemented` | 0 |
| No dependencies (standalone) | 10 |

Note: if ANY dependency is not `implemented`, the requirement CANNOT be selected
regardless of score. This is a hard filter, not a soft score.

**blocking_count:**
- Number of other requirements that list this REQ in their Dependencies
- Higher = more important to do early (unblocks more work)

**complexity_penalty:**
- Number of acceptance criteria in the requirement
- More criteria = more complex = slightly deprioritized
- This is a tiebreaker, not a major factor

**open_questions:**
- Number of unanswered questions in Q-xxx.md for this requirement
- Any open question = -100 = effectively blocked

### Selection Algorithm

```
1. FILTER: status = ready AND all dependencies implemented
2. SCORE: calculate score for each filtered requirement
3. SORT: descending by score
4. TIEBREAK: if scores equal, pick lower REQ number (older = first)
5. SELECT: take the top requirement
```

### Example

```
REQ-001 auth-basic     | critical | deps: none     | blocks: 5 | ACs: 4 | Qs: 0
  score = (10x10) + (10x5) + (5x3) - (4x2) - 0 = 100 + 50 + 15 - 8 = 157

REQ-002 user-profile   | high     | deps: 001 (impl) | blocks: 3 | ACs: 6 | Qs: 0
  score = (7x10) + (10x5) + (3x3) - (6x2) - 0 = 70 + 50 + 9 - 12 = 117

REQ-003 payments       | critical | deps: 001 (impl) | blocks: 2 | ACs: 8 | Qs: 2
  score = (10x10) + (10x5) + (2x3) - (8x2) - 200 = -60  -> BLOCKED by questions

REQ-004 notifications  | medium   | deps: 002 (ready) | blocks: 0 | ACs: 3 | Qs: 0
  -> FILTERED OUT: dependency 002 is not implemented yet
```

Result: Agent picks REQ-001, then REQ-002, skips 003 (questions), skips 004 (deps).

---

## Change Requests vs New Requirements

**CRs ALWAYS take priority over new REQs.**

Processing order:
1. Change Requests with status: `ready` (oldest first by CR number)
2. Requirements with status: `ready` (by score formula above)

Reason: CRs modify existing implemented code. Until they're applied,
the codebase may have inconsistencies between spec and implementation.

---

### Priority Assignment Guide (for Spec Writer Agent)

When the input specifies priority explicitly, use it:
- "must have", "critical", "blocking" -> **critical**
- "important", "should have", "needed" -> **high**
- "nice to have", "would be good" -> **medium**
- "eventually", "later", "if time permits" -> **low**

When not specified:
- Core functionality (auth, data models, CRUD) -> **high**
- User-facing features -> **medium**
- Polish, optimization, nice-to-have -> **low**
- If truly unsure -> **medium** and file a question asking about priority
"""

SPEC_INDEX_MD = """\
# Specification Index

## Selection Algorithm

```
FIRST: Check for Change Requests (CRs) with status: ready -> process those first
THEN:  Select requirements using:
  1. Filter: status = ready
  2. Filter: all dependencies have status = implemented
  3. Score using PRIORITY.md formula
  4. Select highest score
  5. Tiebreak: lower REQ number (older first)
```

See PRIORITY.md for full scoring details.

## Requirements Registry

<!-- Keep this in sync with requirement files. Agent updates on every status change. -->

| ID | Title | Status | Priority | Dependencies | Blocks | Questions | Source |
|----|-------|--------|----------|--------------|--------|-----------|--------|

## Change Requests

<!-- CRs are ALWAYS processed before new REQs -->

| ID | Modifies | Status | Created | Source |
|----|----------|--------|---------|--------|

## Status Legend

### Requirement statuses
- `draft` — has ambiguities, not ready for implementation
- `ready` — fully specified, agent can pick it up
- `blocked` — agent found ambiguities, questions filed
- `in-progress` — agent is currently implementing
- `implemented` — all acceptance criteria met, all tests passing
- `removed` — deleted via Change Request

### Change Request statuses
- `draft` — CR written but not reviewed
- `impact-review` — agent assessed impact, waiting for human review
- `ready` — approved for implementation
- `applied` — changes merged into REQ, done
- `rejected` — decided not to apply

## Dependency Rules

- Agent MUST NOT start a REQ whose dependencies are not ALL `implemented`
- Circular dependencies are a spec error -> file a question
- CRs have implicit dependency on their target REQ being `implemented`
"""

SPEC_WRITER_WORKFLOW = """\
name: Spec Writer

on:
  issues:
    types: [opened, edited]

jobs:
  write-spec:
    if: contains(github.event.issue.labels.*.name, 'feature')
    runs-on: ubuntu-latest
    permissions:
      contents: write
      pull-requests: write
      issues: read

    steps:
      - uses: actions/checkout@v4

      - name: Install Claude Code
        run: npm install -g @anthropic-ai/claude-code

      - name: Run Spec Writer Agent
        env:
          ANTHROPIC_API_KEY: ${{ secrets.ANTHROPIC_API_KEY }}
          GH_TOKEN: ${{ secrets.GITHUB_TOKEN }}
        run: |
          ISSUE_NUMBER="${{ github.event.issue.number }}"
          ISSUE_TITLE="${{ github.event.issue.title }}"
          ISSUE_BODY=$(gh issue view "$ISSUE_NUMBER" --json body -q .body)

          claude -p "Read agents/spec-writer/ROLE.md. You are the Spec Writer agent.
          Load your memory files first.
          Read PRIORITY.md for priority assignment rules.
          Read spec/SPEC_INDEX.md for existing requirements context.

          Your input is GitHub Issue #${ISSUE_NUMBER}:
          Title: ${ISSUE_TITLE}
          Body: ${ISSUE_BODY}

          Process this issue:
          1. Decompose into atomic requirements
          2. Create REQ files in spec/requirements/
          3. Create question files in spec/questions/ if needed
          4. Update spec/SPEC_INDEX.md
          5. Add 'Source: GitHub Issue #${ISSUE_NUMBER}' to each REQ metadata

          IMPORTANT: Set status to 'draft' for all new requirements."

      - name: Create Pull Request
        uses: peter-evans/create-pull-request@v5
        with:
          branch: spec/issue-${{ github.event.issue.number }}
          title: "Spec: ${{ github.event.issue.title }}"
          body: |
            ## Auto-generated spec from #${{ github.event.issue.number }}

            ### Review checklist
            - [ ] Acceptance criteria are specific and testable
            - [ ] Dependencies are correct
            - [ ] Priority is appropriate
            - [ ] Questions (if any) make sense
            - [ ] Change all `status: draft` -> `status: ready` before merging
          labels: spec-review
          commit-message: "spec: add requirements from issue #${{ github.event.issue.number }}"
"""

CODER_AGENT_WORKFLOW = """\
name: Coder Agent

on:
  push:
    branches: [main]
    paths:
      - 'spec/requirements/**.md'
      - 'spec/SPEC_INDEX.md'

  workflow_dispatch:
    inputs:
      max_iterations:
        description: 'Max requirements to implement'
        default: '1'
        type: string

jobs:
  implement:
    runs-on: ubuntu-latest
    permissions:
      contents: write
      pull-requests: write

    steps:
      - uses: actions/checkout@v4
        with:
          fetch-depth: 0

      - name: Check for ready requirements
        id: check
        run: |
          READY_COUNT=$(grep -cE "\\| ready +\\|" spec/SPEC_INDEX.md 2>/dev/null || echo "0")
          echo "ready_count=$READY_COUNT" >> $GITHUB_OUTPUT
          if [ "$READY_COUNT" -eq 0 ]; then
            echo "No ready requirements. Nothing to do."
          fi

      - name: Install Claude Code
        if: steps.check.outputs.ready_count != '0'
        run: npm install -g @anthropic-ai/claude-code

      - name: Setup project dependencies
        if: steps.check.outputs.ready_count != '0'
        run: |
          [ -f "package.json" ] && npm install || true
          [ -f "requirements.txt" ] && pip install -r requirements.txt || true
          [ -f "pyproject.toml" ] && pip install -e ".[dev]" || true
          [ -f "go.mod" ] && go mod download || true

      - name: Run Coder Agent
        if: steps.check.outputs.ready_count != '0'
        env:
          ANTHROPIC_API_KEY: ${{ secrets.ANTHROPIC_API_KEY }}
        run: |
          MAX_ITER="${{ inputs.max_iterations || '1' }}"

          for ((i=1; i<=MAX_ITER; i++)); do
            echo "=== Iteration $i / $MAX_ITER ==="

            READY=$(grep -cE "\\| ready +\\|" spec/SPEC_INDEX.md 2>/dev/null || echo "0")
            if [ "$READY" -eq 0 ]; then
              echo "No more ready requirements."
              break
            fi

            claude -p "Read agents/coder/ROLE.md. You are the Coder agent.
            Read PRIORITY.md for the requirement selection algorithm.
            Read spec/SPEC_INDEX.md.
            Follow the orchestration loop exactly -- Steps 1 through 6.
            If anything is unclear -- write questions and STOP.
            Do NOT implement more than ONE requirement."

            if [ $? -ne 0 ]; then
              echo "Agent exited with error"
              break
            fi

            QUESTIONS=$(grep -rl "Status: open" spec/questions/ 2>/dev/null | wc -l)
            if [ "$QUESTIONS" -gt 0 ]; then
              echo "Agent filed questions. Stopping."
              break
            fi
          done

      - name: Create Pull Request
        if: steps.check.outputs.ready_count != '0'
        uses: peter-evans/create-pull-request@v5
        with:
          branch: impl/run-${{ github.run_id }}
          title: "Implement: auto-run ${{ github.run_id }}"
          body: |
            ## Automated implementation run

            ### Review checklist
            - [ ] All new tests pass
            - [ ] Code matches the requirement acceptance criteria
            - [ ] No extra code beyond what the spec requires
            - [ ] Commits are atomic (one micro-step each)
            - [ ] SPEC_INDEX.md is updated correctly
          labels: code-review
          commit-message: "impl: automated requirement implementation"
"""

ISSUE_TEMPLATE_FEATURE = """\
---
name: Feature Request
about: Describe a feature for the Spec Writer Agent to process
title: "[Feature] "
labels: feature
assignees: ''
---

## Feature: <name>

### What should happen
<!-- Describe the behavior in plain language. Be as specific as you can,
     but don't worry about format — the Spec Writer Agent will formalize it. -->


### Who uses this
<!-- Optional: describe the user/actor -->


### Constraints / important details
<!-- Optional: anything the agent must know — validation rules, limits,
     integrations, things that are explicitly OUT of scope -->


### Priority
<!-- Pick one: critical | high | medium | low -->
medium

### Related issues
<!-- Optional: link to related issues or requirements -->

"""

ISSUE_TEMPLATE_CHANGE = """\
---
name: Change Request
about: Modify or remove an existing feature
title: "[Change] "
labels: change
assignees: ''
---

## Change to: REQ-XXX — <requirement name>

### What should change
<!-- Describe the modification in plain language -->


### Why
<!-- Why is this change needed? -->


### What should NOT change
<!-- Optional but helpful: behaviors that must remain the same -->


### Priority
<!-- Pick one: critical | high | medium | low -->
medium
"""

CLAUDE_SETTINGS_LOCAL_JSON = """\
{
  "hooks": {
    "PreCompact": [
      {
        "matcher": "",
        "hooks": [
          {
            "type": "command",
            "command": "python3 .claude/hooks/precompact_save.py"
          }
        ]
      }
    ]
  }
}
"""

# ── New templates added for improved init ─────────────────────

CLAUDE_MD = """\
# {project_name}

<!-- Fill this before running agents. It is read at the start of every session. -->

## What this project is

<!-- One paragraph: what the system does, who uses it, what problem it solves -->


## Tech stack

<!-- Language, framework, key libraries, database, hosting, etc. -->
<!-- Example:
  - Python 3.13 / FastAPI
  - PostgreSQL (via SQLAlchemy)
  - Redis for caching
  - Deployed on Railway
-->


## Conventions

<!-- Project-specific rules agents must follow.
     Examples: naming conventions, file layout, error handling style,
     test framework, commit message format, etc. -->


## Key concepts / domain vocabulary

<!-- Define terms that are specific to your domain.
     Agents will use these exact words in specs and code. -->


## Important links

<!-- Docs, design files, API references, staging URL, etc. -->


## What NOT to do

<!-- Anti-patterns, explicitly forbidden approaches, deprecated paths -->
"""

GITIGNORE = """\
# Python
__pycache__/
*.py[cod]
*.egg-info/
.venv/
dist/
.pytest_cache/

# Node
node_modules/

# Env
.env
.env.*
!.env.example

# OS
.DS_Store
Thumbs.db

# iEvo
.ievo/cache/

# Claude Code local settings
.claude/settings.local.json
"""

ARCHITECT_WORKFLOW = """\
name: Architect Agent

on:
  push:
    branches: [main]
    paths:
      - 'spec/requirements/**.md'
      - 'spec/SPEC_INDEX.md'

  workflow_dispatch:

jobs:
  plan:
    runs-on: ubuntu-latest
    permissions:
      contents: write
      pull-requests: write

    steps:
      - uses: actions/checkout@v4
        with:
          fetch-depth: 0

      - name: Check for requirements needing plans
        id: check
        run: |
          READY_COUNT=$(grep -cE "\\\\| ready +\\\\|" spec/SPEC_INDEX.md 2>/dev/null || echo "0")
          echo "ready_count=$READY_COUNT" >> $GITHUB_OUTPUT
          if [ "$READY_COUNT" -eq 0 ]; then
            echo "No ready requirements. Nothing to do."
          fi

      - name: Install Claude Code
        if: steps.check.outputs.ready_count != '0'
        run: npm install -g @anthropic-ai/claude-code

      - name: Run Architect Agent
        if: steps.check.outputs.ready_count != '0'
        env:
          ANTHROPIC_API_KEY: ${{ secrets.ANTHROPIC_API_KEY }}
        run: |
          claude -p "Read agents/architect/ROLE.md. You are the Architect agent.
          Load your memory files first.
          Read PRIORITY.md for the requirement selection algorithm.
          Read spec/SPEC_INDEX.md to find the highest-priority ready requirement
          that does not yet have a plan in plans/.
          Create a detailed implementation plan in plans/PLAN-REQ-XXX.md
          following agents/architect/templates/PLAN_TEMPLATE.md.
          Update spec/SPEC_INDEX.md status to in-progress.
          Stop after planning ONE requirement."

      - name: Create Pull Request
        if: steps.check.outputs.ready_count != '0'
        uses: peter-evans/create-pull-request@v5
        with:
          branch: plan/run-${{ github.run_id }}
          title: "Plan: auto-run ${{ github.run_id }}"
          body: |
            ## Auto-generated implementation plan

            ### Review checklist
            - [ ] Plan covers all acceptance criteria
            - [ ] Micro-steps are small and independently committable
            - [ ] Traceability table maps every AC to a step
            - [ ] Scope guard lists explicitly excluded items
          labels: plan-review
          commit-message: "plan: architect implementation plan"
"""

SPEC_REQ_TEMPLATE = """\
# REQ-XXX: <Title>

## Metadata
- **Status:** draft
- **Priority:** <1-10, where 1 is highest>
- **Dependencies:** <REQ-YYY, REQ-ZZZ | none>
- **Created:** <date>
- **Implemented:** <date or empty>

## Context

<!--
IMPORTANT: This section must be SELF-CONTAINED.
The agent reads ONLY this file when implementing.
Include everything it needs to know about the existing system state.
Do NOT write "see REQ-001" — copy the relevant facts here.
-->

Describe what already exists in the system that this requirement interacts with.
Mention specific models, endpoints, modules, and their behavior.

## Acceptance Criteria

<!--
Each criterion = one testable behavior.
Format: Given <precondition> → When <action> → Then <expected result>
Be SPECIFIC about inputs and outputs. No vague language.
-->

- [ ] `<action with specific input>` → `<specific expected output/behavior>`
- [ ] `<action with specific input>` → `<specific expected output/behavior>`
- [ ] `<edge case / error input>` → `<specific error response/behavior>`

## Negative Acceptance Criteria

<!--
What this requirement explicitly does NOT do.
Prevents the agent from over-building.
-->

- This does NOT include <feature X> (see REQ-ZZZ)
- This does NOT handle <edge case Y> — that is out of scope

## Technical Notes

<!--
Optional. Architecture hints, constraints, conventions.
Only include if there are hard technical requirements (e.g., "must use library X").
Leave empty if the agent should decide implementation details.
-->

## Examples

<!--
Optional but recommended. Concrete input/output examples help the agent
write better tests. Format depends on the domain (API requests, function calls, etc.)
-->

### Example 1: <happy path>
```
Input: ...
Output: ...
```

### Example 2: <error case>
```
Input: ...
Output: ...
```
"""

SPEC_CR_TEMPLATE = """\
# CR-XXX: <Title>

## Metadata
- **Modifies:** REQ-XXX
- **Source:** GitHub Issue #N
- **Status:** draft | impact-review | ready | applied
- **Created:** <date>
- **Applied:** <date or empty>

## What Changes

<!-- Quote the EXACT current acceptance criteria being modified, then show the new version -->

### Modified criteria

**Old (REQ-XXX, criterion N):**
```
<exact current text>
```

**New:**
```
<new text>
```

### New criteria added
- [ ] `<new acceptance criterion>`

### Criteria removed
- ~~`<criterion being removed>`~~ — Reason: <why>

## What Stays the Same

<!-- Explicitly list behaviors that are NOT changing. This prevents the agent
     from accidentally breaking things that should remain stable. -->

- <behavior 1> — unchanged
- <behavior 2> — unchanged

## Impact Estimate

<!-- Filled by the Coder Agent during impact-review phase -->

### Tests affected
| Test file | Action | Details |
|-----------|--------|---------|

### Code affected
| Source file | Action | Details |
|-------------|--------|---------|

### Dependent requirements to recheck
| REQ | Status | Risk |
|-----|--------|------|
"""
