import gradio as gr
import os
import time
import tempfile
import traceback
from github_repo_analyzer import get_repo_info, clone_repo, analyze_code, analyze_issues, analyze_pull_requests, llm_analyze_code, llm_analyze_issues, llm_analyze_prs, llm_synthesize_findings, generate_report
from github import Github
from openai import OpenAI

# Emojis and fun statements for progress updates
PROGRESS_STEPS = [
    ("🕵️‍♂️", "Investigating the GitHub realm..."),
    ("🧬", "Decoding repository DNA..."),
    ("🐛", "Hunting for bugs and features..."),
    ("🔍", "Examining pull request tea leaves..."),
    ("🧠", "Activating AI brain cells..."),
    ("📝", "Crafting the legendary report..."),
]

def analyze_github_repo(repo_input, github_token=None):
    base_url = "https://github.com/"
    if github_token:
        os.environ["GITHUB_TOKEN"] = github_token
        base_url = f"https://{github_token}@github.com/"
    
    github_token = os.environ.get("GITHUB_TOKEN")
    if not github_token:
        return "❌ Error: GITHUB_TOKEN environment variable not set.", gr.update(visible=True), gr.update(visible=False)

    openrouter_api_key = os.environ.get("OPENROUTER_API_KEY")
    if not openrouter_api_key:
        return "❌ Error: OPENROUTER_API_KEY environment variable not set.", gr.update(visible=True), gr.update(visible=False)

    progress_md = ""
    yield progress_md, gr.update(visible=True), gr.update(visible=False)  # Initial empty output

    for emoji, message in PROGRESS_STEPS:
        progress_md += f"{emoji} {message}  \n"
        yield progress_md, gr.update(visible=True), gr.update(visible=False)
        time.sleep(4)

    try:
        owner, repo_name = get_repo_info(repo_input)
        repo_url = f"{base_url}/{owner}/{repo_name}"
        
        g = Github(github_token)
        github_repo = g.get_repo(f"{owner}/{repo_name}")
        
        client = OpenAI(api_key=openrouter_api_key, base_url="https://openrouter.ai/api/v1")

        max_issues = 4
        max_prs = 4

        with tempfile.TemporaryDirectory() as temp_dir:
            repo_info = clone_repo(owner, repo_name, temp_dir, repo_url)
            repo_path = repo_info["local_path"]

            progress_md += "🔬 Analyzing code structure...  \n"
            yield progress_md, gr.update(visible=True), gr.update(visible=False)
            code_analysis = analyze_code(repo_path)
            code_analysis['llm_analysis'] = llm_analyze_code(client, code_analysis)

            progress_md += f"📊 Analyzing issues (max {max_issues})...  \n"
            yield progress_md, gr.update(visible=True), gr.update(visible=False)
            issues_data = analyze_issues(github_repo, max_issues)
            issues_analysis = llm_analyze_issues(client, issues_data, repo_url)

            progress_md += f"🔀 Analyzing pull requests (max {max_prs})...  \n"
            yield progress_md, gr.update(visible=True), gr.update(visible=False)
            prs_data = analyze_pull_requests(github_repo, max_prs)
            pr_analysis = llm_analyze_prs(client, prs_data, repo_url)

            # progress_md += "🧠 Synthesizing findings...  \n"
            # yield progress_md, gr.update(visible=True), gr.update(visible=False)
            # final_analysis = llm_synthesize_findings(
            #     client, 
            #     code_analysis.get('llm_analysis', ''),
            #     issues_analysis.get('summary', ''),
            #     pr_analysis.get('summary', '')
            # )

            progress_md += "📝 Generating report...  \n"
            yield progress_md, gr.update(visible=True), gr.update(visible=False)
            report = generate_report(repo_info, code_analysis, issues_analysis, pr_analysis)

        # Return the final Markdown report
        yield progress_md + "✅ Analysis complete!", gr.update(visible=False), gr.update(visible=True, value=report)
    except Exception as e:
        error_message = f"❌ An error occurred: {str(e)}"
        traceback.print_exc()
        yield progress_md + error_message, gr.update(visible=True), gr.update(visible=False)
        
html = """<iframe src="https://ghbtns.com/github-btn.html?user=patched-codes&repo=patchwork&type=star&count=true&size=large" frameborder="0" scrolling="0" width="170" height="30" title="GitHub"></iframe>
"""
# Define the Gradio interface
with gr.Blocks() as app:
    gr.Markdown("# Patched GitHub Repo Analyzer")
    gr.Markdown("## Build and run your identified workflows with [patched](https://patched.codes)")
    gr.HTML(html)
    
    repo_input = gr.Textbox(label="Enter GitHub Repository Slug or URL")
    
    with gr.Accordion("Advanced Settings", open=False):
        github_token = gr.Textbox(label="GitHub Token (optional)", type="password")
    
    analyze_button = gr.Button("Analyze Repository")
    
    progress_output = gr.Markdown(label="Progress")
    report_output = gr.Markdown(label="Analysis Report", visible=False)
    
    analyze_button.click(
        analyze_github_repo,
        inputs=[repo_input, github_token],
        outputs=[progress_output, progress_output, report_output],
    )

# Launch the app
if __name__ == "__main__":
    app.launch()