import os
import pytest
import asyncio
from dotenv import load_dotenv
from opengit.agents import core
from src.mcp.knowledge_graph_mcp import audit_repository, calculate_tech_debt_score
from src.mcp.green_optimizer_mcp import get_carbon_intensity

load_dotenv()

@pytest.mark.asyncio
async def test_production_gitlab_connection():
    """Verify real connectivity to GitLab API."""
    import gitlab
    token = os.environ.get("GITLAB_TOKEN")
    project_path = os.environ.get("OPENGIT_PROJECT")
    assert token, "GITLAB_TOKEN missing"
    assert project_path, "OPENGIT_PROJECT missing"
    
    gl = gitlab.Gitlab("https://gitlab.com", private_token=token)
    proj = gl.projects.get(project_path)
    assert proj.path_with_namespace == project_path

@pytest.mark.asyncio
async def test_production_anthropic_triage():
    """Verify real connectivity to Anthropic Claude."""
    from src.mcp.claude_analyst_mcp import triage_failure
    api_key = os.environ.get("ANTHROPIC_API_KEY")
    assert api_key, "ANTHROPIC_API_KEY missing"
    
    result = await triage_failure("Test failure logs", scenario="dependency_drift")
    assert "learning_moment" in result
    assert "powered_by" in result
    assert result["powered_by"] == "Anthropic Claude"

@pytest.mark.asyncio
async def test_production_green_optimizer():
    """Verify real connectivity to Electricity Maps (if key present)."""
    api_key = os.environ.get("ELECTRICITY_MAPS_API_KEY")
    result = await get_carbon_intensity("US-CAL-CISO")
    assert "intensity" in result
    assert "sci_score" in result

@pytest.mark.asyncio
async def test_production_tech_debt_scan():
    """Run real Tech Debt scan on the target project."""
    project_path = os.environ.get("OPENGIT_PROJECT")
    result = await calculate_tech_debt_score(project_path)
    assert "total_score" in result
    assert "breakdown" in result

@pytest.mark.asyncio
async def test_production_audit_scan():
    """Run real security audit (read-only scan)."""
    project_path = os.environ.get("OPENGIT_PROJECT")
    findings = await audit_repository(project_path)
    assert isinstance(findings, list)
    # Findings may be empty if the repo is clean, which is fine
