import byzerllm


@byzerllm.prompt()
def _plan_format() -> str:
    """
    # Plan File Specification: Structured Project Planning for AI

    ## What is a Plan File?

    **Plan File** (`.plan.md`) is a structured document that helps AI and humans collaborate on project planning and task tracking.

    Think of it as a project brief that contains:

    1. Metadata about the plan (name, overview, todos)
    2. Detailed technical design and implementation steps
    3. Visual diagrams for complex workflows
    4. Acceptance criteria for validation

    ## Basic Structure

    A plan file has two main parts:

    ```
    ---
    YAML Front Matter (metadata)
    ---

    Markdown Body (detailed content)
    ```

    ## Part 1: YAML Front Matter

    The front matter is enclosed in `---` delimiters and contains structured metadata.

    ### Required Fields

    ```yaml
    ---
    name: my-feature-plan
    overview: One or two sentences describing what this plan achieves.
    todos:
      - id: step-1
        content: Description of the first task
        status: completed
      - id: step-2
        content: Description of the second task
        status: in_progress
      - id: step-3
        content: Description of the third task
        status: pending
    ---
    ```

    ### Field Specifications

    | Field | Type | Required | Description |
    |-------|------|----------|-------------|
    | `name` | string | Yes | Unique identifier (lowercase, hyphen-separated) |
    | `overview` | string | Yes | Brief description of the plan's goal |
    | `todos` | array | Yes | List of task items (can be empty `[]`) |
    | `isProject` | boolean | No | Whether this is a multi-file project plan |

    ### Todo Item Structure

    Each todo item has three fields:

    | Field | Type | Values | Description |
    |-------|------|--------|-------------|
    | `id` | string | - | Unique task identifier (lowercase, hyphen-separated) |
    | `content` | string | - | Task description in one sentence |
    | `status` | enum | `pending`, `in_progress`, `completed` | Current task state |

    ### Status Meanings

    | Status | Meaning |
    |--------|---------|
    | `pending` | Not yet started |
    | `in_progress` | Currently being worked on |
    | `completed` | Successfully finished |

    ## Part 2: Markdown Body Sections

    The markdown body follows the YAML front matter and contains detailed planning information.

    ### Common Sections

    #### 1. 目标与约束 / Goals and Constraints

    Clearly state what the plan aims to achieve and any limitations:

    ```markdown
    ## 目标与约束

    - **目标**：Implement feature X that allows users to do Y.
    - **约束**：
      - Must be backward compatible with existing API
      - Performance must not degrade by more than 5%
      - Must follow existing code style conventions
    ```

    #### 2. 设计概要 / Design Overview

    High-level technical design:

    ```markdown
    ## 设计概要

    - **Architecture**: Describe the overall structure
    - **Key Components**: List the main modules involved
    - **Data Flow**: Explain how data moves through the system
    ```

    #### 3. 命令设计 / CLI Design

    For CLI tools, document the command structure:

    ```markdown
    ## 命令设计

    - `tool command --flag value`
      - Returns: description of output
    - `tool subcommand action <arg> --option`
      - Supports: list of supported values
    ```

    #### 4. 代码改动点 / Code Changes

    List specific files and what changes are needed:

    ```markdown
    ## 代码改动点

    ### 1) File: `path/to/file.py`

    - Add new function `process_data()`
    - Modify class `DataHandler` to support streaming
    - Update imports to include new dependencies

    ### 2) File: `path/to/another_file.py`

    - Rename `old_method()` to `new_method()`
    - Add error handling for edge cases
    ```

    #### 5. 目录结构 / Directory Structure

    For new modules, show the planned file layout:

    ```markdown
    ## 目录结构

    ```
    new_module/
    ├── main.py
    ├── cmd/
    │   ├── root.py
    │   └── subcommand.py
    ├── internal/
    │   ├── client.py
    │   └── utils.py
    └── README.md
    ```
    ```

    #### 6. 数据流 / Data Flow

    Use Mermaid diagrams for complex flows:

    ```markdown
    ## 数据流

    ```mermaid
    flowchart TD
        A[User Input] --> B[Validator]
        B --> C{Valid?}
        C -->|Yes| D[Processor]
        C -->|No| E[Error Handler]
        D --> F[Output]
    ```
    ```

    #### 7. 测试与验证 / Testing and Validation

    Define how to verify the implementation:

    ```markdown
    ## 测试与验证

    - **Unit Tests**:
      - Test input parsing with edge cases
      - Test error handling paths
    - **Integration Tests**:
      - End-to-end workflow validation
    - **Manual Verification**:
      - Command X should output Y
    ```

    #### 8. 风险与边界 / Risks and Edge Cases

    Document potential issues:

    ```markdown
    ## 风险与边界

    - **Risk 1**: Description and mitigation strategy
    - **Edge Case**: How the system handles unusual inputs
    - **Limitation**: Known limitations of the implementation
    ```

    #### 9. 验收标准 / Acceptance Criteria

    Clear criteria for completion:

    ```markdown
    ## 验收标准

    - [ ] All todos marked as completed
    - [ ] Unit tests pass
    - [ ] Documentation updated
    - [ ] Code review approved
    ```

    ## Mermaid Diagram Types

    ### Flowchart (most common)

    ```mermaid
    flowchart TD
        A[Start] --> B{Decision}
        B -->|Yes| C[Action 1]
        B -->|No| D[Action 2]
        C --> E[End]
        D --> E
    ```

    ### Sequence Diagram (for interactions)

    ```mermaid
    sequenceDiagram
        participant User
        participant CLI
        participant API
        participant Database

        User->>CLI: command --args
        CLI->>API: request
        API->>Database: query
        Database-->>API: result
        API-->>CLI: response
        CLI-->>User: output
    ```

    ### State Diagram (for status flows)

    ```mermaid
    flowchart LR
        A[pending] --> B[in_progress]
        B --> C[completed]
        B --> D[error]
        D --> A
    ```

    ## Complete Example

    Here is a complete plan file example:

    ```markdown
    ---
    name: user-auth-refactor
    overview: Refactor authentication module to support OAuth2 and improve token management with caching.
    todos:
      - id: define-interfaces
        content: Define new auth provider interfaces for OAuth2 and API key authentication
        status: completed
      - id: implement-oauth
        content: Implement OAuth2 provider with token refresh logic
        status: in_progress
      - id: add-caching
        content: Add token caching layer with configurable TTL
        status: pending
      - id: migration-guide
        content: Write migration guide for existing users
        status: pending
    isProject: false
    ---

    # User Authentication Refactor

    ## 目标与约束

    - **目标**：Modernize the authentication system to support multiple auth providers.
    - **约束**：
      - Maintain backward compatibility with existing API key auth
      - OAuth tokens must be cached to reduce API calls
      - Support both sync and async usage patterns

    ## 设计概要

    - **Provider Interface**: Abstract base class for all auth providers
    - **Token Cache**: Redis-backed cache with fallback to in-memory
    - **Refresh Logic**: Automatic token refresh before expiration

    ## 代码改动点

    ### 1) `internal/auth/provider.py`

    - New file: Define `AuthProvider` abstract base class
    - Methods: `authenticate()`, `refresh()`, `validate()`

    ### 2) `internal/auth/oauth.py`

    - Implement `OAuthProvider(AuthProvider)`
    - Handle authorization code flow
    - Implement token refresh with retry logic

    ### 3) `internal/cache/token_cache.py`

    - New file: Token caching with TTL
    - Support Redis and in-memory backends

    ## 数据流

    ```mermaid
    sequenceDiagram
        participant Client
        participant AuthManager
        participant Cache
        participant OAuthProvider
        participant ExternalAPI

        Client->>AuthManager: authenticate()
        AuthManager->>Cache: get_token()
        alt Token cached and valid
            Cache-->>AuthManager: token
        else Token missing or expired
            AuthManager->>OAuthProvider: authenticate()
            OAuthProvider->>ExternalAPI: OAuth flow
            ExternalAPI-->>OAuthProvider: tokens
            OAuthProvider-->>AuthManager: tokens
            AuthManager->>Cache: set_token(tokens)
        end
        AuthManager-->>Client: authenticated
    ```

    ## 测试与验证

    - **Unit Tests**:
      - Provider interface compliance
      - Token refresh edge cases
      - Cache expiration behavior
    - **Integration Tests**:
      - Full OAuth flow with mock server
      - Cache failover scenarios

    ## 验收标准

    - [ ] All existing tests pass
    - [ ] New unit tests for OAuth provider
    - [ ] Integration tests for token caching
    - [ ] Documentation updated with new auth options
    ```

    ## Best Practices

    ### 1. Keep Todos Actionable

    ❌ Bad:
    ```yaml
    todos:
      - id: do-stuff
        content: Work on the feature
        status: pending
    ```

    ✅ Good:
    ```yaml
    todos:
      - id: implement-parser
        content: Implement JSON parser with streaming support for large files
        status: pending
    ```

    ### 2. Use Consistent ID Naming

    - Use lowercase with hyphens: `implement-auth`, `add-tests`
    - Be specific: `oauth-token-refresh` instead of `step-3`
    - Keep IDs stable once created (for tracking)

    ### 3. Order Todos by Dependency

    List tasks in the order they should be executed:

    ```yaml
    todos:
      - id: define-types
        content: Define data types and interfaces
        status: completed
      - id: implement-core
        content: Implement core logic using defined types
        status: in_progress
      - id: add-tests
        content: Add unit tests for core logic
        status: pending
      - id: integrate
        content: Integrate with existing system
        status: pending
    ```

    ### 4. Use Diagrams for Complex Flows

    When a process involves:
    - Multiple components interacting
    - Decision points or branching logic
    - Async or parallel operations
    - State transitions

    Always add a Mermaid diagram to clarify.

    ### 5. Link to Existing Files

    Reference existing code files with full paths:

    ```markdown
    - 参考现有实现：`[agent_excel/cmd/root.go](/path/to/agent_excel/cmd/root.go)`
    - 复用输出格式：对齐 `internal/output/output.go` 的 `{success, data, error}` 结构
    ```

    ### 6. Define Clear Acceptance Criteria

    Make verification checkable:

    ❌ Vague:
    ```markdown
    - Should work correctly
    - Tests should pass
    ```

    ✅ Specific:
    ```markdown
    - [ ] `command --help` displays all options with descriptions
    - [ ] JSON output matches schema: `{"success": bool, "data": object, "error": string}`
    - [ ] Unit test coverage > 80% for new code
    ```

    ## Plan File Storage and Naming Convention

    ### Storage Location

    Plan files should be stored in the `~/.auto-coder/plans` directory:

    ```
    ~/.auto-coder/plans/
    ├── user-auth-refactor_a1b2c3d4e5f6.plan.md
    ├── api-streaming_b2c3d4e5f6a7.plan.md
    └── add-calendar-tool_c3d4e5f6a7b8.plan.md
    ```

    ### Naming Rules

    Plan files **MUST** follow these naming conventions:

    | Rule | Description | Example |
    |------|-------------|---------|
    | **English only** | Use English characters only, no Chinese or other non-ASCII characters | ✅ `add-calendar` ❌ `新增日历` |
    | **No spaces** | Use hyphens (`-`) instead of spaces | ✅ `user-auth-refactor` ❌ `user auth refactor` |
    | **UUID suffix** | End with a UUID (or short UUID) for uniqueness | ✅ `feature_a1b2c3d4` |
    | **Lowercase** | Use lowercase letters | ✅ `api-streaming` ❌ `API-Streaming` |
    | **`.plan.md` extension** | Always use `.plan.md` as the file extension | ✅ `feature_uuid.plan.md` |

    ### Naming Pattern

    ```
    <feature-name>_<uuid>.plan.md
    ```

    Where:
    - `<feature-name>`: Descriptive name in English, hyphen-separated, lowercase
    - `<uuid>`: A UUID or short UUID (8+ characters recommended) for uniqueness
    - `.plan.md`: Required file extension

    ### Examples

    ✅ Good:
    - `user-auth-refactor_a1b2c3d4e5f6.plan.md`
    - `api-streaming_ee04e53f.plan.md`
    - `add-calendar-tool_cc06e6a5.plan.md`
    - `database-migration_550e8400-e29b-41d4-a716-446655440000.plan.md`

    ❌ Bad:
    - `新增日历工具_cc06e6a5.plan.md` (contains Chinese characters)
    - `user auth refactor.plan.md` (contains spaces, missing UUID)
    - `API-Streaming.plan.md` (uppercase, missing UUID)
    - `feature.md` (wrong extension, missing UUID)

    ## Summary

    > **Plan File = YAML Front Matter (name + overview + todos) + Markdown Body (goals + design + changes + diagrams + tests + criteria)**
    """
