"""SEF Agents Generator.

Generates AGENTS.md with SEF protocol and mandatory fix workflow.

Usage:
    from sef_agents.tools.agents_generator import generate_agents_file
    result = generate_agents_file("/path/to/project")
"""

from pathlib import Path

import structlog

logger = structlog.get_logger(__name__)


AGENTS_MD_CONTENT = """# AI Coding Assistant Protocol

## Non-Negotiable Policies

### SEF-Agents MCP Entry Point Requirement

**CRITICAL:** If `sef-agents` MCP is enabled and available, **ALL tasks MUST be performed via one of the sef-agent instances**. Direct code execution or modifications that bypass sef-agents are prohibited.

**Enforcement:**
- Check sef-agents MCP availability before any task execution
- Delegate all tasks to appropriate sef-agent roles when MCP is active
- Do not bypass agent roles if MCP is configured

---

## Communication Style (Non-Negotiable)

**Core Directive:** BE LACONIC. Eliminate conversational filler.

- **Token Efficiency:** If 2 words suffice, do not use 10.
- **No Fluff:** Omit "Here is the code," "I have analyzed," or "It is important to." Just state facts or output code.
- **Tone:** Direct, Professional, Technical.

**Readability Constraints:**

| Metric | Target | Guideline |
|--------|--------|-----------|
| **Grade Level** | 8.0 – 10.0 | Simple prose reduces cognitive load. |
| **Sentence Length** | 15–20 words | No nested sentences. Avoid verbosity tax. |
| **Vocabulary** | Technical | Use precise jargon (e.g., "idempotency") over flowery descriptions. |
| **Voice** | Active | "Service scales..." NOT "Scaling is handled by..." |

---

## Mandatory Fix Workflow

> [!IMPORTANT]
> **This workflow is MANDATORY for all code fixes.** Non-compliance blocks deployment.

### Fix Definition

A **fix** is any code change that addresses a defect, regression, or unexpected behavior in existing functionality. This includes:

- Bug fixes
- Error corrections
- Performance regressions
- Security patches

**New features and enhancements are NOT fixes.**

### Workflow Sequence

```
1. forensic_engineer → RCA & Root Cause Identification
2. strategist       → Solution Design & Trade-off Analysis
3. developer        → Implementation
```

### Step Details

| Step | Agent | Responsibility | Output |
|------|-------|----------------|--------|
| **1** | `forensic_engineer` | Investigate root cause, analyze logs/code, produce RCA | `sef-reports/post-mortem-*.md` |
| **2** | `strategist` | Evaluate fix approaches, trade-off analysis, recommend solution | Solution recommendation |
| **3** | `developer` | Implement approved fix, write tests | Code changes + tests |

### Context Requirement

**Before starting any fix, consult `codemap/` to:**

1. Understand codebase structure
2. Locate relevant module/implementation
3. Identify dependencies and integration boundaries

### Enforcement

- Skipping `forensic_engineer` → **BLOCKED** at PR review
- Skipping `strategist` for non-trivial fixes → **BLOCKED** at PR review
- Direct fixes without RCA → **REJECTED**

---

## Engineering Standards

- **Production Ready:** Solutions must be robust, scalable, and secure. No temporary patches.
- **Conservation:** Do not modify working code unless explicitly requested for optimization.
- **Isolation:** Fixes must be targeted. Do not expand scope without permission.
- **File Operations:** If a file requires renaming or moving, perform the move/rename action. **DO NOT** regenerate the code content.

---

## Available Agents

| Agent | Role | When to Use |
|-------|------|-------------|
| `discovery` | Codebase exploration | Initial project understanding |
| `forensic_engineer` | Root cause analysis | Investigating failures/bugs |
| `strategist` | Solution design | Planning approaches |
| `architect` | System design | Architecture decisions |
| `developer` | Implementation | Writing/modifying code |
| `tester` | Quality assurance | Test design and execution |
| `security_owner` | Security review | Security audits |
| `docs_curator` | Documentation | Updating docs |
| `pr_reviewer` | Code review | Reviewing changes |
| `platform_engineer` | Infrastructure | CI/CD, health scans |

---

*Generated by SEF Discovery Agent. Do not edit manually.*
"""


def generate_agents_file(directory: str) -> str:
    """Generate AGENTS.md at project root.

    Args:
        directory: Path to project root.

    Returns:
        Status message.
    """
    root = Path(directory)

    if not root.exists():
        return f"Error: Directory {directory} does not exist."

    agents_path = root / "AGENTS.md"

    # Always overwrite - this is a protocol file
    agents_path.write_text(AGENTS_MD_CONTENT, encoding="utf-8")

    logger.info("agents_md_generated", path=str(agents_path))

    return f"✅ AGENTS.md generated at `{agents_path}`"
