"""LLM-enhanced rule generator using Anthropic API."""

import os
from typing import List, Optional
from ..models import FailureRecord, RuleSuggestion


def generate_with_llm(
    records: List[FailureRecord],
    agents_md_content: Optional[str] = None,
) -> List[RuleSuggestion]:
    """Generate rule suggestions using the Anthropic API.

    Requires ANTHROPIC_API_KEY environment variable.
    """
    # Import only when needed
    try:
        import anthropic
    except ImportError:
        raise ImportError(
            "anthropic package is required for LLM mode. Install with: pip install anthropic"
        )

    api_key = os.environ.get("ANTHROPIC_API_KEY")
    if not api_key:
        raise ValueError(
            "ANTHROPIC_API_KEY environment variable is not set. "
            "Set it to use LLM mode, or omit --llm to use pattern-based analysis."
        )

    client = anthropic.Anthropic(api_key=api_key)

    # Build failure summary
    failure_lines = []
    for i, record in enumerate(records[:20], 1):  # Cap at 20 records
        failure_lines.append(f"{i}. [{record.type}] {record.message[:200]}")

    failures_text = "\n".join(failure_lines) if failure_lines else "No specific failures provided."

    # Build prompt
    agents_section = ""
    if agents_md_content:
        # Truncate to avoid token limits
        truncated = agents_md_content[:3000]
        agents_section = f"""
Current AGENTS.md content (for context, avoid duplicates):
```
{truncated}
```
"""

    prompt = f"""You are helping a developer improve their AGENTS.md file — a set of rules for AI coding agents like Claude Code or Codex.

The following failures were detected from their agent's recent work:

{failures_text}
{agents_section}
Based on these failures, suggest 3-5 specific, actionable rules that would prevent these failures in the future.

Requirements:
- Each rule should be a single, concrete action item
- Rules should be specific enough to be immediately actionable
- Avoid vague advice like "be careful" — give specific patterns, checks, or practices
- Format each rule as a markdown list item starting with "- "
- Focus on preventing the exact type of failure shown

Respond ONLY with the markdown list items, nothing else."""

    message = client.messages.create(
        model="claude-3-5-haiku-latest",
        max_tokens=1024,
        messages=[{"role": "user", "content": prompt}],
    )

    response_text = message.content[0].text.strip()

    # Parse the response into RuleSuggestion objects
    suggestions = []
    for line in response_text.splitlines():
        line = line.strip()
        if line.startswith("- "):
            text = line[2:].strip()
            if text:
                # Remove markdown checkbox if present
                if text.startswith("[ ] "):
                    text = text[4:]
                suggestions.append(
                    RuleSuggestion(
                        category="llm-generated",
                        text=text,
                        confidence=0.85,
                        source="anthropic/claude-3-5-haiku-latest",
                    )
                )

    return suggestions
