"""Artifact compiler for generating agent-specific configuration files."""

from __future__ import annotations

from pathlib import Path

from .models import (
    CompilationContext,
    PolicyRule,
    ScopeRules,
    SessionConfig,
    Severity,
)

# Markers for the EgoKit-managed section in AGENTS.md
# Content between these markers is auto-generated; content outside is human-managed
EGOKIT_BEGIN_MARKER = "<!-- BEGIN-EGOKIT-POLICIES -->"
EGOKIT_END_MARKER = "<!-- END-EGOKIT-POLICIES -->"


def find_egokit_section(content: str) -> tuple[int, int] | None:
    """Find the EgoKit-managed section in existing AGENTS.md content.

    Args:
        content: Existing AGENTS.md content

    Returns:
        Tuple of (start_index, end_index) if markers found, None otherwise.
        The indices include the markers themselves.
    """
    begin_idx = content.find(EGOKIT_BEGIN_MARKER)
    if begin_idx == -1:
        return None

    end_idx = content.find(EGOKIT_END_MARKER, begin_idx)
    if end_idx == -1:
        return None

    # Include the end marker itself
    end_idx += len(EGOKIT_END_MARKER)
    return (begin_idx, end_idx)


def extract_human_content(content: str) -> tuple[str, str]:
    """Extract human-managed content before and after the EgoKit section.

    Args:
        content: Existing AGENTS.md content

    Returns:
        Tuple of (before_content, after_content). If no markers found,
        returns (content, "") - all content is considered "before".
    """
    section = find_egokit_section(content)
    if section is None:
        return (content, "")

    begin_idx, end_idx = section
    before = content[:begin_idx].rstrip()
    after = content[end_idx:].lstrip()
    return (before, after)


class ArtifactCompiler:
    """Compiles policy and ego configurations into agent-specific artifacts."""

    def __init__(self, context: CompilationContext) -> None:
        """Initialize compiler with compilation context.

        Args:
            context: Compilation context containing merged policies and ego config
        """
        self.context = context

    def compile_egokit_section(self) -> str:
        """Generate the EgoKit-managed section for AGENTS.md.

        This method generates only the policy content that EgoKit manages,
        wrapped in BEGIN/END markers. Human-authored content outside
        these markers is preserved when injecting into existing files.

        Returns:
            Markdown content for the EgoKit-managed section, including markers
        """
        rules = self._extract_rules_from_charter()
        timestamp = self.context.generation_timestamp.strftime("%Y-%m-%d")
        sections: list[str] = []

        # Opening marker with warning
        sections.extend([
            EGOKIT_BEGIN_MARKER,
            "<!-- ⚠️ Auto-generated by EgoKit. Do not edit manually. -->",
            f"<!-- Run `ego apply` to regenerate. Last updated: {timestamp} -->",
            "",
        ])

        # Policy Compliance (the binding section)
        sections.extend(self._compile_agents_policy_compliance(rules))

        # Testing Instructions
        testing_rules = [r for r in rules if "testing" in (r.tags or [])]
        if testing_rules:
            sections.extend(self._compile_agents_testing(testing_rules))

        # Security Considerations
        security_rules = [r for r in rules if "security" in (r.tags or [])]
        if security_rules:
            sections.extend(self._compile_agents_security(security_rules))

        # Session Protocol (opt-in)
        session = self.context.policy_charter.session
        if session is not None:
            sections.extend(self._compile_agents_session_protocol(session))

        # EgoKit Commands Reference
        sections.extend(self._compile_agents_commands_reference())

        # EgoKit Configuration Pointer
        sections.extend(self._compile_agents_configuration_pointer())

        # Closing marker
        sections.append(EGOKIT_END_MARKER)

        return "\n".join(sections)

    def generate_agents_md_template(self) -> str:
        """Generate a full AGENTS.md template for new projects.

        This creates a complete file with placeholder sections for human
        authoring, plus the EgoKit-managed policy section.

        Returns:
            Complete AGENTS.md content with placeholders and policy section
        """
        ego = self.context.ego_config
        sections: list[str] = []

        # Header
        sections.extend([
            "# AGENTS.md",
            "",
        ])

        # Project Overview (human-managed with defaults)
        sections.extend([
            "## Project Overview",
            "",
            "<!-- Edit this section to describe your project -->",
            "",
            f"You are a **{ego.role}** working on this codebase.",
            "",
        ])

        if ego.tone:
            sections.extend([
                f"**Communication Style:** {ego.tone.voice}",
                f"**Verbosity:** {ego.tone.verbosity}",
                "",
            ])

        if ego.defaults:
            sections.append("**Development Approach:**")
            for key, value in ego.defaults.items():
                readable_key = key.replace("_", " ").title()
                sections.append(f"- {readable_key}: {value}")
            sections.append("")

        # Setup Commands (human-managed)
        sections.extend(self._compile_agents_setup_commands())

        # Code Style (human-managed with defaults from config)
        style_rules = [r for r in self._extract_rules_from_charter()
                       if self._has_style_tags(r)]
        if style_rules:
            sections.extend(self._compile_agents_code_style(style_rules))
        else:
            sections.extend([
                "## Code Style",
                "",
                "<!-- Edit this section to document your coding conventions -->",
                "",
                "- Follow project conventions",
                "- See linter configuration for formatting rules",
                "",
            ])

        # Architecture (human-managed placeholder)
        sections.extend([
            "## Architecture",
            "",
            "<!-- Edit this section to describe your project's architecture -->",
            "",
            "- [Describe key components here]",
            "- [Document important design decisions]",
            "",
        ])

        # Add the EgoKit-managed section
        sections.append(self.compile_egokit_section())

        return "\n".join(sections)

    def inject_egokit_section(self, existing_content: str | None) -> str:
        """Inject or replace the EgoKit section in existing AGENTS.md content.

        Args:
            existing_content: Existing AGENTS.md content, or None for new file

        Returns:
            Updated AGENTS.md content with EgoKit section injected/replaced
        """
        if existing_content is None:
            return self.generate_agents_md_template()

        egokit_section = self.compile_egokit_section()
        section_bounds = find_egokit_section(existing_content)

        if section_bounds is not None:
            # Replace existing section
            begin_idx, end_idx = section_bounds
            before = existing_content[:begin_idx].rstrip()
            after = existing_content[end_idx:].lstrip()

            parts = [before]
            if before:
                parts.append("\n\n")
            parts.append(egokit_section)
            if after:
                parts.append("\n\n")
                parts.append(after)
            return "".join(parts)

        # Append section to end (caller should confirm with user first)
        content = existing_content.rstrip()
        return f"{content}\n\n{egokit_section}\n"

    def _has_style_tags(self, rule: PolicyRule) -> bool:
        """Check if rule has style-related tags."""
        style_tags = {"style", "formatting", "code-style", "naming", "conventions"}
        return bool(set(rule.tags or []) & style_tags)

    def _extract_rules_from_charter(self) -> list[PolicyRule]:
        """Extract all rules from the policy charter."""
        rules: list[PolicyRule] = []

        for scope_data in self.context.policy_charter.scopes.values():
            if isinstance(scope_data, ScopeRules):
                # Handle ScopeRules object
                rules.extend(scope_data.all_rules())
            elif isinstance(scope_data, dict):
                # Handle dict format (legacy or from YAML)
                for category_rules in scope_data.values():
                    if isinstance(category_rules, list):
                        for rule_dict in category_rules:
                            try:
                                rule = PolicyRule.model_validate(rule_dict)
                                rules.append(rule)
                            except (ValueError, TypeError):
                                # Skip invalid rules
                                continue

        return rules

    def _compile_agents_project_overview(self) -> list[str]:
        """Generate Project Overview section for AGENTS.md."""
        ego = self.context.ego_config
        sections = [
            "## Project Overview",
            "",
            f"You are a **{ego.role}** working on this codebase.",
            "",
        ]

        if ego.tone:
            sections.extend([
                f"**Communication Style:** {ego.tone.voice}",
                f"**Verbosity:** {ego.tone.verbosity}",
                "",
            ])

        if ego.defaults:
            sections.append("**Development Approach:**")
            for key, value in ego.defaults.items():
                readable_key = key.replace("_", " ").title()
                sections.append(f"- {readable_key}: {value}")
            sections.append("")

        return sections

    def _compile_agents_setup_commands(self) -> list[str]:
        """Generate Setup Commands section for AGENTS.md."""
        sections = [
            "## Setup Commands",
            "",
        ]

        # Check for setup info in charter metadata
        metadata = self.context.policy_charter.metadata
        if "setup" in metadata:
            setup = metadata["setup"]
            if isinstance(setup, dict):
                for cmd_name, cmd_value in setup.items():
                    sections.append(f"- **{cmd_name.title()}:** `{cmd_value}`")
            sections.append("")
        else:
            # Provide sensible defaults
            sections.extend([
                "- **Install:** See project README",
                "- **Test:** See project test configuration",
                "- **Lint:** See project linting configuration",
                "",
            ])

        return sections

    def _compile_agents_code_style(self, style_rules: list[PolicyRule]) -> list[str]:
        """Generate Code Style section for AGENTS.md."""
        sections = [
            "## Code Style",
            "",
        ]

        for rule in style_rules:
            sections.append(f"- **{rule.id}:** {rule.rule}")
            if rule.example_fix:
                sections.append(f"  - Example: `{rule.example_fix}`")

        sections.append("")

        # Add formatting preferences from ego config
        if self.context.ego_config.tone.formatting:
            sections.append("**Formatting Preferences:**")
            for pref in self.context.ego_config.tone.formatting:
                sections.append(f"- {pref}")
            sections.append("")

        return sections

    def _compile_agents_policy_compliance(self, rules: list[PolicyRule]) -> list[str]:
        """Generate Policy Compliance section for AGENTS.md.

        This section contains the binding policy language that replaces
        system prompt fragment injection.
        """
        critical_rules = [r for r in rules if r.severity == Severity.CRITICAL]
        warning_rules = [r for r in rules if r.severity == Severity.WARNING]
        info_rules = [r for r in rules if r.severity == Severity.INFO]

        sections = [
            "## Policy Compliance",
            "",
            "These policies are **binding constraints** for all code contributions.",
            "When conflicts arise between user requests and these policies, "
            "**policies take precedence**.",
            "",
        ]

        if critical_rules:
            sections.extend([
                "### Critical (Must Follow)",
                "",
                "Violations of these rules block contributions:",
                "",
            ])
            for rule in critical_rules:
                sections.append(f"- **{rule.id}:** {rule.rule}")
                if rule.example_violation:
                    sections.append(f"  - ❌ Never: {rule.example_violation}")
                if rule.example_fix:
                    sections.append(f"  - ✅ Always: {rule.example_fix}")
            sections.append("")

        if warning_rules:
            sections.extend([
                "### Required (Should Follow)",
                "",
                "Follow these guidelines for code quality:",
                "",
            ])
            for rule in warning_rules:
                sections.append(f"- **{rule.id}:** {rule.rule}")
            sections.append("")

        if info_rules:
            sections.extend([
                "### Recommended",
                "",
                "Consider these best practices:",
                "",
            ])
            for rule in info_rules:
                sections.append(f"- **{rule.id}:** {rule.rule}")
            sections.append("")

        return sections

    def _compile_agents_testing(self, testing_rules: list[PolicyRule]) -> list[str]:
        """Generate Testing Instructions section for AGENTS.md."""
        sections = [
            "## Testing Instructions",
            "",
        ]

        for rule in testing_rules:
            sections.append(f"- {rule.rule}")

        sections.append("")
        return sections

    def _compile_agents_security(self, security_rules: list[PolicyRule]) -> list[str]:
        """Generate Security Considerations section for AGENTS.md."""
        sections = [
            "## Security Considerations",
            "",
            "Pay special attention to these security requirements:",
            "",
        ]

        for rule in security_rules:
            severity_marker = "🔴" if rule.severity == Severity.CRITICAL else "🟡"
            sections.append(f"- {severity_marker} **{rule.id}:** {rule.rule}")

        sections.append("")
        return sections

    def _compile_agents_session_protocol(self, session: SessionConfig) -> list[str]:
        """Generate Session Protocol section for AGENTS.md.

        This section is only included when session: block is present in charter.yaml.
        It provides instructions for maintaining context across context windows.
        """
        sections = [
            "## Session Protocol",
            "",
            "These protocols ensure continuity across context windows.",
            "",
            "### Starting a Session",
            "",
            "Before beginning new work:",
            "",
        ]

        # Startup: Read context files
        if session.startup.read:
            sections.append("1. **Read context files** (in order):")
            for file_path in session.startup.read:
                sections.append(f"   - `{file_path}`")
            sections.append("")

        # Startup: Run orientation commands
        if session.startup.run:
            sections.append("2. **Check repository state**:")
            sections.append("   ```bash")
            for cmd in session.startup.run:
                sections.append(f"   {cmd}")
            sections.append("   ```")
            sections.append("")

        sections.extend([
            "3. **Verify clean handoff**:",
            "   - No uncommitted changes from previous session",
            "   - Progress file updated within reasonable timeframe",
            "",
            "### Ending a Session",
            "",
            "Before ending work or when context window is filling:",
            "",
        ])

        # Shutdown: Commit requirement
        step = 1
        if session.shutdown.commit:
            sections.append(
                f"{step}. **Commit all changes** with descriptive message "
                "following commit conventions",
            )
            sections.append("")
            step += 1

        # Shutdown: Update progress files
        if session.shutdown.update:
            progress_file = session.shutdown.update[0] if session.shutdown.update else "PROGRESS.md"
            sections.append(f"{step}. **Update progress file** (`{progress_file}`):")
            sections.extend([
                "   ```markdown",
                "   ## Session: YYYY-MM-DD",
                "   ",
                "   ### Completed",
                "   - [What was accomplished]",
                "   ",
                "   ### Next Steps",
                "   - [What remains to be done]",
                "   ",
                "   ### Blockers",
                "   - [Any issues encountered]",
                "   ",
                "   ### Files Modified",
                "   - [List of changed files]",
                "   ```",
                "",
            ])
            step += 1

        sections.extend([
            f"{step}. **Verify clean state**:",
            "   - All tests pass",
            "   - No unfinished TODOs in modified code",
            "",
        ])

        return sections

    def _compile_agents_commands_reference(self) -> list[str]:
        """Generate EgoKit Commands reference section for AGENTS.md."""
        return [
            "## EgoKit Commands",
            "",
            "This project uses EgoKit for policy management. Available commands:",
            "",
            "- `/ego-validate` — Check current work against policies",
            "- `/ego-rules` — View active policies",
            "- `/ego-stats` — Analyze violation patterns from git history",
            "- `/ego-suggest` — Propose new rules based on codebase patterns",
            "- `/ego-checkpoint` — Pre-change compliance snapshot",
            "- `/ego-review` — Pre-commit review checklist",
            "- `/ego-security` — Activate security-focused mode",
            "- `/ego-refresh` — Re-read policy context",
            "- `/ego-persona` — Switch working persona (developer, writer, reviewer, architect)",
            "",
        ]

    def _compile_agents_configuration_pointer(self) -> list[str]:
        """Generate configuration pointer section for AGENTS.md.

        This helps AI agents understand how to modify EgoKit policies
        when users ask to add or change rules.
        """
        # Get registry path relative info if available
        registry_hint = ".egokit/policy-registry/"

        return [
            "## Modifying Policies",
            "",
            f"To add or change policies, edit `{registry_hint}charter.yaml` "
            "and run `ego apply`.",
            "The charter file contains schema documentation in its comments.",
            "",
            "---",
            "",
            f"*Policy Charter Version: {self.context.policy_charter.version}*",
            "",
        ]

    def compile_all_artifacts(
        self,
        existing_agents_md: str | None = None,
    ) -> dict[str, str]:
        """Generate all artifacts: AGENTS.md and slash commands for both tools.

        This is the primary compilation method for the AGENTS.md-first approach.
        It generates:
        - AGENTS.md (the universal policy artifact)
        - .claude/commands/ego-*.md (Claude Code slash commands)
        - .augment/commands/ego-*.md (Auggie CLI slash commands)

        For AGENTS.md, uses hybrid ownership model:
        - If existing_agents_md is None: generates full template with placeholders
        - If existing_agents_md has markers: replaces content between markers
        - If existing_agents_md has no markers: appends section (caller should confirm)

        Args:
            existing_agents_md: Existing AGENTS.md content, or None if file
                doesn't exist

        Returns:
            Dictionary mapping file paths to their content
        """
        artifacts: dict[str, str] = {}

        # Generate AGENTS.md using injection/template approach
        artifacts["AGENTS.md"] = self.inject_egokit_section(existing_agents_md)

        # Generate slash commands for both tool directories
        commands = self.compile_slash_commands()
        for cmd_name, cmd_content in commands.items():
            artifacts[f".claude/commands/{cmd_name}"] = cmd_content
            artifacts[f".augment/commands/{cmd_name}"] = cmd_content

        return artifacts

    def compile_slash_commands(self) -> dict[str, str]:
        """Generate slash commands for both Claude Code and Auggie CLI.

        All commands use the 'ego-' prefix to avoid collision with built-in
        commands. Commands are pure AI prompts with no CLI/bash dependencies.

        Returns:
            Dictionary mapping command filenames to their content.
            Keys are like 'ego-validate.md', values are the markdown content.
        """
        commands: dict[str, str] = {}

        # Core policy commands
        commands["ego-validate.md"] = self._generate_ego_validate_command()
        commands["ego-rules.md"] = self._generate_ego_rules_command()
        commands["ego-stats.md"] = self._generate_ego_stats_command()
        commands["ego-suggest.md"] = self._generate_ego_suggest_command()

        # Workflow commands
        commands["ego-checkpoint.md"] = self._generate_ego_checkpoint_command()
        commands["ego-review.md"] = self._generate_ego_review_command()
        commands["ego-security.md"] = self._generate_ego_security_command()
        commands["ego-refresh.md"] = self._generate_ego_refresh_command()
        commands["ego-persona.md"] = self._generate_ego_persona_command()

        return commands

    def _generate_ego_validate_command(self) -> str:
        """Generate /ego-validate command as pure AI prompt."""
        return """---
description: Validate current work against organizational policies
argument-hint: [file/path]
---

# Validate Against Policies

Review the code for compliance with this project's policies defined in AGENTS.md.

## Instructions

1. Read the "Policy Compliance" section from AGENTS.md in this repository
2. Analyze the specified file (or current file if none specified, or staged
   changes if no file context)
3. For each applicable policy rule:
   - Check if the code complies
   - Note any violations with the rule ID and explanation
4. Summarize findings:
   - ✅ Compliant rules
   - ⚠️ Warnings (non-blocking)
   - ❌ Violations (must fix)

## Output Format

For each issue found:
```
[RULE-ID] severity: description
  → file:line - specific issue
  → Suggested fix: ...
```

If no issues: "✅ All policies satisfied."
"""

    def _generate_ego_rules_command(self) -> str:
        """Generate /ego-rules command as pure AI prompt."""
        return """---
description: Display active policies for this project
argument-hint: [category]
---

# Show Active Policies

Display the organizational policies that govern this project.

## Instructions

1. Read AGENTS.md from this repository
2. Extract the "Policy Compliance" section
3. If a category is specified, filter to that category
4. Present rules organized by severity:
   - 🔴 Critical (must follow)
   - 🟡 Warning (should follow)
   - 🔵 Info (recommendations)

## Output Format

For each rule:
```
[RULE-ID] (severity): Brief description
  Tags: tag1, tag2
```

Include a count summary at the end.
"""

    def _generate_ego_stats_command(self) -> str:
        """Generate /ego-stats command as pure AI prompt."""
        return """---
description: Analyze policy compliance patterns from git history
argument-hint: [--days N] [--branch main]
---

# Policy Compliance Statistics

Analyze the git history to identify policy-related patterns and trends.

## Context Check (Important)

First, determine the context:
1. Check current branch with `git branch --show-current`
2. If on a feature/refactor branch, note that high commit rates and frequent
   fixes are EXPECTED and should not be flagged as quality concerns
3. For accurate violation analysis, compare against main/master branch or
   use `--branch main` to analyze only merged commits

## Instructions

1. Run `git log --oneline -100` (or filter by --days if specified)
2. Distinguish between:
   - **Intentional iteration**: Same author refining work on a feature branch
   - **Actual violations**: Commits explicitly fixing policy breaches (look for
     rule IDs like SEC-001, QUAL-001, etc. in messages)
   - **Refactoring work**: Commits with "refactor:", "chore:" are planned
     improvements, not quality problems
3. Look for genuine policy signals:
   - Commits that explicitly mention rule IDs or "policy"
   - Patterns where different authors fix the same type of issue
   - Post-merge fixes that correct violations missed in review
4. Summarize findings with appropriate context

## Output Format

```
## Analysis Context
- Branch: [current branch]
- Analysis type: [feature branch iteration | main branch history]

## Compliance Trends (last N commits)

### Policy Adherence
- [RULE-ID]: Evidence of compliance or violation

### Frequently Changed Areas
- path/to/file.py - N commits ([iteration on feature | potential hotspot])

### Patterns Observed
- [PATTERN]: Description (noting if this is expected refactoring)

### Recommendations
- [Only suggest rules for genuine gaps, not iteration noise]
```

## Important

Do NOT interpret high fix/chore commit rates as quality problems when:
- Analyzing a feature or refactor branch (iteration is normal)
- Commits are from the same author refining their own work
- The branch name suggests intentional restructuring
"""

    def _generate_ego_suggest_command(self) -> str:
        """Generate /ego-suggest command as pure AI prompt."""
        return """---
description: Suggest new policy rules based on codebase patterns
argument-hint: [focus-area]
---

# Suggest New Policies

Analyze the codebase to propose new policy rules for charter.yaml.

## Instructions

1. Scan the codebase for consistent patterns:
   - Naming conventions in use
   - Error handling patterns
   - Documentation styles
   - Import organization
   - Testing patterns
2. Compare against existing rules in AGENTS.md
3. Identify gaps where patterns exist but no rule enforces them
4. Generate charter.yaml entries for suggested rules

## Output Format

For each suggestion:
```yaml
# Suggested rule: [brief description]
# Rationale: [why this pattern should be codified]
- id: SUGGESTED-XXX
  rule: "Description of the rule"
  severity: warning  # or critical
  tags: [relevant, tags]
  detector: "suggested-detector-name.v1"
```

Group suggestions by category (style, security, documentation, etc.)
"""

    def _generate_ego_checkpoint_command(self) -> str:
        """Generate /ego-checkpoint command as pure AI prompt.

        If session protocol is configured, includes session handoff template.
        """
        session = self.context.policy_charter.session

        base_command = """---
description: Pre-change compliance snapshot or session handoff
argument-hint: [task-description | --handoff]
---

# Checkpoint

Create a compliance snapshot before changes, or prepare a session handoff.

## Mode: Pre-Change Checkpoint

If preparing for code changes:

1. Read AGENTS.md to understand active policies
2. Analyze the current state of files you plan to modify
3. Identify which policy rules apply to your planned changes
4. Create a checklist of compliance requirements

### Pre-Change Output Format

```
## Checkpoint: [timestamp]

### Files to Modify
- file1.py - current status
- file2.py - current status

### Applicable Policies
- [RULE-ID]: How it applies to this change
- [RULE-ID]: How it applies to this change

### Pre-Change Checklist
- [ ] Policy requirement 1
- [ ] Policy requirement 2

### Notes
Any special considerations or risks
```
"""

        if session is not None:
            progress_file = session.progress_file or "PROGRESS.md"
            handoff_section = f"""
## Mode: Session Handoff

If ending a session or context window is filling (use `--handoff`):

1. Commit all pending changes with descriptive message
2. Update `{progress_file}` with session summary
3. Verify clean handoff state

### Session Handoff Checklist

- [ ] All changes committed
- [ ] Progress file updated
- [ ] All tests pass
- [ ] No unfinished TODOs in modified files

### Progress File Template

Use this template when updating `{progress_file}`:

```markdown
## Session: [DATE]

### Completed
- [What was accomplished this session]

### Next Steps
- [What remains to be done]
- [Priority order if applicable]

### Blockers
- [Any issues encountered]
- [Questions that need answers]

### Files Modified
- [List of files changed]
```
"""
            base_command += handoff_section

        base_command += """
Use checkpoints to maintain continuity and validate your work.
"""

        return base_command

    def _generate_ego_review_command(self) -> str:
        """Generate /ego-review command as pure AI prompt."""
        return """---
description: Pre-commit review against policies
argument-hint: [--staged]
---

# Pre-Commit Policy Review

Review staged or recent changes against organizational policies before committing.

## Instructions

1. Read AGENTS.md to load active policies
2. Analyze staged changes (run `git diff --staged`) or recent uncommitted changes
3. For each changed file:
   - Identify applicable policy rules
   - Check compliance with each rule
   - Note any violations or concerns
4. Provide a commit readiness assessment

## Output Format

```
## Pre-Commit Review

### Changes Reviewed
- file1.py: +10/-5 lines
- file2.py: +3/-0 lines

### Policy Compliance
✅ [RULE-ID]: Compliant
❌ [RULE-ID]: Issue found - [description]
⚠️ [RULE-ID]: Warning - [description]

### Commit Readiness
[READY/NOT READY]: [summary]

### Required Actions (if not ready)
1. Fix issue X
2. Address warning Y
```
"""

    def _generate_ego_security_command(self) -> str:
        """Generate /ego-security command as pure AI prompt."""
        return """---
description: Activate security-focused review mode
argument-hint: [path/file]
---

# Security-Focused Review Mode

Analyze code with heightened security awareness.

## Instructions

1. Read the Security Considerations section from AGENTS.md
2. Apply security-focused analysis to the specified code:
   - Input validation and sanitization
   - Authentication and authorization checks
   - Secrets and credential handling
   - SQL injection and XSS prevention
   - Cryptographic implementation review
   - Dependency vulnerability awareness
3. Flag any security concerns with severity levels

## Output Format

```
## Security Review: [file/path]

### Critical Issues (must fix)
- [location]: [issue description]
  → Recommended fix: [solution]

### Warnings (should address)
- [location]: [concern]
  → Consideration: [guidance]

### Security Checklist
- [x] No hardcoded secrets
- [x] Inputs validated
- [ ] Issue: [description]

### Risk Assessment
[LOW/MEDIUM/HIGH]: [summary of security posture]
```
"""

    def _generate_ego_refresh_command(self) -> str:
        """Generate /ego-refresh command as pure AI prompt.

        If session protocol is configured, includes session startup checklist.
        If not configured, includes a hint about the feature.
        """
        session = self.context.policy_charter.session

        base_command = """---
description: Re-read and internalize policy context
---

# Refresh Policy Context

Re-read AGENTS.md to ensure current policy awareness.

## Instructions

1. Read the complete AGENTS.md file
2. Summarize the key policies you must follow
3. Confirm your understanding of:
   - Critical rules that must never be violated
   - Required practices for code quality
   - Security considerations
"""

        if session is not None:
            # Include session startup protocol
            session_section = """
## Session Startup

If this is a new session or context window:

"""
            # Add files to read
            if session.startup.read:
                session_section += "**Read context files:**\n"
                for file_path in session.startup.read:
                    session_section += f"- `{file_path}`\n"
                session_section += "\n"

            # Add commands to run
            if session.startup.run:
                session_section += "**Check repository state:**\n```bash\n"
                for cmd in session.startup.run:
                    session_section += f"{cmd}\n"
                session_section += "```\n\n"

            session_section += (
                "**Verify:**\n"
                "- No uncommitted changes from previous session\n"
                "- Progress file is up to date\n"
            )

            base_command += session_section

        base_command += """
4. Acknowledge the refresh with a brief summary

## Output Format

```
## Policy Refresh Complete

### Critical Policies (must follow)
- [RULE-ID]: [brief description]
- [RULE-ID]: [brief description]

### Key Requirements
- [requirement 1]
- [requirement 2]

### Security Focus Areas
- [area 1]
- [area 2]
"""

        if session is not None:
            base_command += """
### Session Status
- Progress file: [status]
- Uncommitted changes: [yes/no]
"""

        base_command += """
Policies refreshed and internalized.
```

Run this command periodically during long sessions to prevent policy drift.
"""

        if session is None:
            base_command += """
---
**Tip:** Add a `session:` block to charter.yaml for session continuity protocols.
"""

        return base_command

    def _generate_ego_persona_command(self) -> str:
        """Generate /ego-persona command as pure AI prompt."""
        return """---
description: Switch to a specific working persona
argument-hint: <developer|writer|reviewer|architect>
---

# Switch Working Persona

Adopt a distinct working persona that changes how you approach tasks.

## Available Personas

### developer (default)
Implementation-focused. Prioritize:
- Code correctness and quality
- Testing and validation
- Following established patterns
- Practical, working solutions

### writer
Technical documentation focus. Prioritize:
- Clarity and readability for the target audience
- Structured information architecture
- Consistent terminology and style
- Reference DOCUMENTATION.md guidelines if present
- No jargon without explanation
- Examples that illuminate concepts

### reviewer
Critical analysis mode. Prioritize:
- Finding issues, not fixing them
- Security, performance, and maintainability concerns
- Asking clarifying questions
- Noting what's missing, not just what's wrong
- Providing actionable feedback

### architect
System-level thinking. Prioritize:
- Trade-off analysis and long-term implications
- Component boundaries and interfaces
- Scalability and extensibility considerations
- Diagrams and visual explanations when helpful
- Questioning assumptions about requirements

## Instructions

1. Acknowledge the persona switch
2. Adjust your approach according to the persona's priorities
3. Maintain the persona until explicitly changed or session ends
4. If no persona specified, show this list

## Output Format

```
Switched to [persona] persona.

Now prioritizing: [key focus areas]
```
"""


class ArtifactInjector:
    """Injects compiled artifacts into target repositories.

    This class provides a simple interface for writing artifacts to disk.
    The CLI uses direct file writing, but this class is kept for backward
    compatibility with existing code that may depend on it.
    """

    def __init__(self, target_repo: Path) -> None:
        """Initialize injector with target repository path.

        Args:
            target_repo: Path to target repository
        """
        self.target_repo = Path(target_repo)

    def inject_artifacts(self, artifacts: dict[str, str]) -> None:
        """Write artifacts to the target repository.

        Args:
            artifacts: Dictionary mapping relative paths to content
        """
        for artifact_path, content in artifacts.items():
            target_path = self.target_repo / artifact_path
            target_path.parent.mkdir(parents=True, exist_ok=True)
            target_path.write_text(content, encoding="utf-8")
