import os
import vertexai
from vertexai.generative_models import GenerativeModel
from mcp.server.fastmcp import FastMCP

# Initialize FastMCP for Gemini Analyst
mcp = FastMCP("GeminiAnalyst")

def _get_gemini_model():
    project_id = os.environ.get("GOOGLE_CLOUD_PROJECT", "codepartnering-484708")
    vertexai.init(project=project_id, location="us-central1")
    return GenerativeModel("gemini-2.0-flash-exp")

@mcp.tool()
async def triage_failure_gemini(logs: str, scenario: str = "generic", package: str = "") -> dict:
    """
    Uses Google Vertex AI Gemini 2.0 to triage a failure.
    Provides multi-AI reasoning alongside Claude.
    """
    model = _get_gemini_model()
    prompt = f"""
    You are OpenGit Gemini Analyst, a proactive SRE guardian.
    Analyze this failure in a GitLab repository:
    Scenario: {scenario}
    Package: {package}
    Logs:
    {logs}
    
    Task:
    1. Identify root cause.
    2. Provide a 'Learning Moment' for the dev team.
    3. Suggest a precise fix.
    
    Respond in JSON:
    {{
        "reason": "...",
        "learning_moment": "...",
        "suggested_fix": "...",
        "powered_by": "Vertex AI Gemini"
    }}
    """
    response = model.generate_content(prompt)
    try:
        import json
        # Extract JSON from response (Gemini might wrap in backticks)
        text = response.text
        if "```json" in text:
            text = text.split("```json")[1].split("```")[0]
        return json.loads(text)
    except:
        return {
            "reason": "Gemini analysis error",
            "learning_moment": "System was unable to parse Gemini output.",
            "suggested_fix": "Review logs manually.",
            "powered_by": "Vertex AI Gemini"
        }

if __name__ == "__main__":
    mcp.run()
