"""Bernard LLM integration — calls LiteLLM for code review and failure analysis."""
from __future__ import annotations

import os

from langchain_openai import ChatOpenAI
from langchain_core.messages import HumanMessage, SystemMessage


def _llm() -> ChatOpenAI:
    return ChatOpenAI(
        model=os.environ.get("BERNARD_MODEL", "ollama-qwen"),
        openai_api_key=os.environ["LITELLM_API_KEY"],
        openai_api_base=os.environ.get("LITELLM_BASE_URL", "http://litellm.ai-core.svc.cluster.local:4000"),
        temperature=0.3,
        timeout=600.0,
    )


async def review_code_diff(title: str, author: str, diff: str) -> str:
    """Review a git diff and return a markdown-formatted code review."""
    llm = _llm()
    system = SystemMessage(content="""You are Bernard, an expert code reviewer for a Kubernetes GitOps platform.
Review the provided git diff and provide structured feedback covering:
1. **Security Issues** — Any secrets, vulnerabilities, or auth problems
2. **Infrastructure Risks** — Misconfigurations, missing health probes, resource limits
3. **Code Quality** — Logic errors, anti-patterns, or improvements
4. **Summary** — Overall assessment (Approve / Request Changes / Needs Discussion)

Be concise and actionable. Format your response in markdown.""")

    # Truncate diff if too large
    diff_truncated = diff[:6000] + "\n... [diff truncated]" if len(diff) > 6000 else diff

    user = HumanMessage(content=f"""**PR Title:** {title}
**Author:** {author}

**Diff:**
```diff
{diff_truncated}
```""")

    response = await llm.ainvoke([system, user])
    return response.content


async def analyze_workflow_failure(workflow_id: str, workflow_type: str, error: str) -> str:
    """Analyze a Temporal workflow failure and suggest a fix."""
    llm = _llm()
    system = SystemMessage(content="""You are Bernard, an expert in Temporal workflow orchestration and LangGraph agents.
Analyze the provided workflow failure and provide:
1. **Root Cause** — What caused the failure
2. **Impact** — What was affected (data loss risk, user impact)
3. **Recommended Fix** — Concrete steps to resolve the issue
4. **Prevention** — How to prevent this in the future

Be concise and technical. Format your response in markdown.""")

    user = HumanMessage(content=f"""**Workflow ID:** {workflow_id}
**Workflow Type:** {workflow_type}

**Error:**
```
{error[:3000]}
```""")

    response = await llm.ainvoke([system, user])
    return response.content
