import os
import git
from typing import List
from rich.console import Console

console = Console()

class GitPortal:
    """
    Phase 5: The 'Ambassador' - Autonomous Git & PR Portal.
    Handles branch creation, committing fixes, and preparing for PR submission.
    """
    def __init__(self, repo_path: str = "."):
        self.repo_path = repo_path
        try:
            self.repo = git.Repo(repo_path)
        except Exception as e:
            self.repo = None
            console.print(f"[red]❌ Git initialization failed: {e}[/red]")

    def create_fix_branch(self, branch_name: str):
        """Creates and switches to a new branch for fixes."""
        if not self.repo: return None
        
        current = self.repo.active_branch
        console.print(f"🌿 [dim]Creating fix branch: {branch_name} (from {current.name})[/dim]")
        
        new_branch = self.repo.create_head(branch_name)
        new_branch.checkout()
        return new_branch

    def commit_fixes(self, files: List[str], message: str):
        """Stages and commits the remediated files."""
        if not self.repo: return False
        
        self.repo.index.add(files)
        self.repo.index.commit(message)
        console.print(f"📦 [bold green]Committed fixes to {len(files)} files.[/bold green]")
        return True

    def push_fixes(self, branch_name: str):
        """Pushes the branch to the remote."""
        if not self.repo: return False
        
        try:
            origin = self.repo.remote(name='origin')
            console.print(f"🚀 [cyan]Pushing {branch_name} to origin...[/cyan]")
            origin.push(branch_name)
            return True
        except Exception as e:
            console.print(f"[yellow]⚠️  Push failed (Remote likely not configured): {e}[/yellow]")
            return False

    def get_pr_body(self, findings_count: int, score_improvement: int):
        """Generates the body text for a GitHub PR."""
        return f"""
# 🕹️ AgentOps Cockpit: Autonomous Room Fixest
**Status**: AUTO_REMEDIATION_COMPLETE
**Maturity Score Improvement**: +{score_improvement}%

## 🛠️ Summary of Remediations
This PR was automatically generated by the AgentOps Cockpit (v1.1) to resolve **{findings_count} architectural gaps**.

### 🧗 Resiliency Hardening
- Injected `tenacity` retry decorators on volatile network calls.
- Applied `timeout` guards to async tool executions to prevent Zombie processes.

### 🛡️ Security Posture
- Resolved hardcoded credential risks via AST detection.
- Fixed behavioral PII leaks identified in runtime traces.

---
*Generated autonomously by the AgentOps Cockpit 'The Closer' Engine.*
"""
