import os
import requests
from typing import Optional, Dict, Any

class GitHubCIHook:
    def __init__(self, token: Optional[str] = None):
        """
        Initializes the GitHub CI Hook.
        :param token: Optional GitHub Personal Access Token. Defaults to GITHUB_TOKEN environment variable.
        """
        self.token = token or os.environ.get("GITHUB_TOKEN")
        self.base_url = "https://api.github.com"
        
    def _get_headers(self) -> Dict[str, str]:
        headers = {
            "Accept": "application/vnd.github.v3+json",
        }
        if self.token:
            headers["Authorization"] = f"Bearer {self.token}"
        return headers

    def fetch_pr_diff(self, repo: str, pr_num: int) -> str:
        """
        Fetches the diff for a given pull request.
        :param repo: The repository in the format "owner/repo"
        :param pr_num: The pull request number
        :return: The PR diff as a string
        """
        url = f"{self.base_url}/repos/{repo}/pulls/{pr_num}"
        headers = self._get_headers()
        # GitHub API requires a specific Accept header to get the diff
        headers["Accept"] = "application/vnd.github.v3.diff"
        
        response = requests.get(url, headers=headers)
        response.raise_for_status()
        return response.text

    def post_review(self, repo: str, pr_num: int, body: str) -> Dict[str, Any]:
        """
        Posts a review comment to a given pull request.
        :param repo: The repository in the format "owner/repo"
        :param pr_num: The pull request number
        :param body: The review comment body
        :return: The JSON response from the API
        """
        # Using the Issue Comments API to post a general review comment on the PR
        url = f"{self.base_url}/repos/{repo}/issues/{pr_num}/comments"
        headers = self._get_headers()
        payload = {"body": body}
        
        response = requests.post(url, headers=headers, json=payload)
        response.raise_for_status()
        return response.json()
