# BRYNQ SWARM - ZERO-TRUST GITHUB MCP SERVER
# [AUTOGENERATED BY TOOL_SMITH_01 | CONSTRUCTIVE MODE]
# Description: Provides Vanguard agents with bounded, read-only access to GitHub.

import os
import httpx
from typing import Dict, Any, List
from pydantic import BaseModel

class GitHubToolConfig(BaseModel):
    # Enforcing strict read-only parameters
    allow_writes: bool = False
    max_files_per_query: int = 5

class GitHubMCP:
    def __init__(self):
        self.base_url = "https://api.github.com"
        # The key should be injected via environment, NEVER hardcoded
        self.token = os.environ.get("GITHUB_PAT")
        self.headers = {
            "Accept": "application/vnd.github.v3+json",
            "User-Agent": "Brynq-Enterprise-Swarm",
            "Authorization": f"Bearer {self.token}" if self.token else ""
        }

    async def fetch_issue(self, owner: str, repo: str, issue_number: int) -> Dict[str, Any]:
        """Tool: Allows an agent to read a specific GitHub issue."""
        if not self.token:
            return {"error": "GITHUB_PAT environment variable is missing. Zero-Trust lock engaged."}
            
        async with httpx.AsyncClient() as client:
            url = f"{self.base_url}/repos/{owner}/{repo}/issues/{issue_number}"
            response = await client.get(url, headers=self.headers)
            
            if response.status_code == 200:
                data = response.json()
                return {
                    "title": data.get("title"),
                    "body": data.get("body"),
                    "state": data.get("state"),
                    "user": data.get("user", {}).get("login")
                }
            return {"error": f"GitHub API returned status {response.status_code}"}

    async def read_file(self, owner: str, repo: str, path: str) -> Dict[str, Any]:
        """Tool: Allows an agent to read a specific file from a repository."""
        if not self.token:
            return {"error": "GITHUB_PAT missing."}
            
        async with httpx.AsyncClient() as client:
            url = f"{self.base_url}/repos/{owner}/{repo}/contents/{path}"
            response = await client.get(url, headers=self.headers)
            
            if response.status_code == 200:
                # Content is base64 encoded by GitHub API, decode in production
                return {"file_info": "File located", "encoding": "base64", "content": response.json().get("content")}
            return {"error": f"File not found or access denied. Status {response.status_code}"}

# Expose standard entrypoint for the Brynq Dispatcher
def get_mcp_manifest():
    return {
        "name": "github_readonly_mcp",
        "version": "1.0.0",
        "tools": ["fetch_issue", "read_file"]
    }