"""
Specialized LLM Analyzers

Provides specialized analysis tools for different content types including
pull requests, code, issues, and GitHub issue vibe checks.
"""

import logging
from typing import Dict, Any, Optional, List

from vibe_check.tools.shared.claude_integration import analyze_content_async
from vibe_check.tools.shared.github_abstraction import get_default_github_operations
from .llm_models import ExternalClaudeResponse
from .text_analyzer import analyze_text_llm

logger = logging.getLogger(__name__)


def _check_common_file_patterns(pr_diff: str, repository: str) -> str:
    """
    Check for common file patterns that are often unnecessarily suggested.

    Returns context string about existing implementations to prevent redundant suggestions.
    Uses regex to match actual file additions in git diff format.
    """
    import re

    context_parts = []

    # Check for barrel exports (index.ts/js files) - match actual file additions
    if re.search(r"^\+\+\+ b/.*index\.(ts|js)$", pr_diff, re.MULTILINE):
        context_parts.append(
            "✅ Barrel exports already implemented (index files found in PR)"
        )

    # Check for README files - match actual file additions
    if re.search(r"^\+\+\+ b/.*README\.md$", pr_diff, re.MULTILINE | re.IGNORECASE):
        context_parts.append(
            "✅ Documentation already present (README files found in PR)"
        )

    # Check for common directory structures - match actual directories being added
    common_patterns = [
        r"validators/",
        r"transformers/",
        r"constants/",
        r"utils/",
        r"helpers/",
    ]
    found_patterns = []
    for pattern in common_patterns:
        if re.search(rf"^\+\+\+ b/.*{pattern}", pr_diff, re.MULTILINE):
            found_patterns.append(pattern.rstrip("/"))
    if found_patterns:
        context_parts.append(
            f"✅ Well-organized modular structure detected: {', '.join(found_patterns)}"
        )

    # Check for TypeScript/configuration files - match actual file additions
    config_patterns = [r"\.eslintrc", r"tsconfig\.json", r"prettier\.config"]
    for pattern in config_patterns:
        if re.search(rf"^\+\+\+ b/.*{pattern}", pr_diff, re.MULTILINE):
            context_parts.append("✅ Code quality tooling already configured")
            break

    if context_parts:
        return f"""
**EXISTING IMPLEMENTATIONS DETECTED:**
{chr(10).join(f'- {item}' for item in context_parts)}

❗ IMPORTANT: Do not suggest adding these features - they are already implemented!
"""
    return ""


def _extract_code_context(
    file_content: str, target_line: int, context_lines: int = 5
) -> str:
    """
    Extract code context around a specific line number.

    Args:
        file_content: Full file content as string
        target_line: Line number to center on (1-indexed)
        context_lines: Number of lines before and after to include

    Returns:
        Code snippet with line numbers
    """
    try:
        lines = file_content.split("\n")
        start_line = max(0, target_line - context_lines - 1)
        end_line = min(len(lines), target_line + context_lines)

        context_snippet = []
        for i in range(start_line, end_line):
            line_num = i + 1
            prefix = ">>> " if line_num == target_line else "    "
            context_snippet.append(f"{prefix}{line_num:3d}: {lines[i]}")

        return "\n".join(context_snippet)
    except Exception:
        return ""


async def analyze_pr_llm(
    pr_diff: str,
    pr_description: str = "",
    file_changes: Optional[List[str]] = None,
    timeout_seconds: int = 90,
    model: str = "sonnet",
) -> ExternalClaudeResponse:
    """
    Comprehensive PR review using Claude CLI reasoning.
    Docs: https://github.com/kesslerio/vibe-check-mcp/blob/main/data/tool_descriptions.json
    """
    logger.info("Starting external PR review")

    # Validate input - detect if URL was passed instead of diff content
    if pr_diff.startswith(("http://", "https://", "github.com", "api.github.com")):
        error_msg = (
            "❌ Invalid input: analyze_pr_llm expects actual PR diff content, not a URL.\n\n"
            f"Received: {pr_diff}\n\n"
            "💡 Use one of these tools instead:\n"
            "  • review_pr_comprehensive(pr_number, repository) - Full PR review with GitHub integration\n"
            "  • analyze_pr_nollm(pr_number, repository) - Fast pattern detection without LLM\n\n"
            "These tools will fetch the PR data from GitHub automatically."
        )
        logger.error(error_msg)
        return ExternalClaudeResponse(
            success=False,
            output=None,
            error=error_msg,
            exit_code=1,
            execution_time_seconds=0.0,
            task_type="pr_review",
        )

    # Validate that pr_diff has content
    if not pr_diff or len(pr_diff.strip()) < 50:
        error_msg = (
            "❌ Invalid input: pr_diff is too short or empty.\n\n"
            "Expected: Git diff output (typically starts with 'diff --git' or has file changes)\n"
            f"Received: {len(pr_diff)} characters\n\n"
            "💡 This tool requires actual diff content. Use review_pr_comprehensive() instead "
            "if you want to analyze a PR by number."
        )
        logger.error(error_msg)
        return ExternalClaudeResponse(
            success=False,
            output=None,
            error=error_msg,
            exit_code=1,
            execution_time_seconds=0.0,
            task_type="pr_review",
        )

    # Build context
    context_parts = []
    if pr_description:
        context_parts.append(f"PR Description: {pr_description}")
    if file_changes:
        context_parts.append(f"Changed files: {', '.join(file_changes)}")

    additional_context = "\n".join(context_parts) if context_parts else None

    return await analyze_text_llm(
        content=pr_diff,
        task_type="pr_review",
        additional_context=additional_context,
        timeout_seconds=timeout_seconds,
        model=model,
    )


async def analyze_code_llm(
    code_content: str,
    file_path: Optional[str] = None,
    language: Optional[str] = None,
    timeout_seconds: int = 60,
    model: str = "sonnet",
) -> ExternalClaudeResponse:
    """
    Deep code analysis using Claude CLI reasoning.
    Docs: https://github.com/kesslerio/vibe-check-mcp/blob/main/data/tool_descriptions.json
    """
    logger.info(f"Starting external code analysis for {language or 'unknown'} code")

    # Build context
    context_parts = []
    if file_path:
        context_parts.append(f"File: {file_path}")
    if language:
        context_parts.append(f"Language: {language}")

    additional_context = "\n".join(context_parts) if context_parts else None

    return await analyze_text_llm(
        content=code_content,
        task_type="code_analysis",
        additional_context=additional_context,
        timeout_seconds=timeout_seconds,
        model=model,
    )


async def analyze_issue_llm(
    issue_content: str,
    issue_title: str = "",
    issue_labels: Optional[List[str]] = None,
    timeout_seconds: int = 60,
    model: str = "sonnet",
) -> ExternalClaudeResponse:
    """
    GitHub issue analysis using Claude CLI reasoning.
    Docs: https://github.com/kesslerio/vibe-check-mcp/blob/main/data/tool_descriptions.json
    """
    logger.info("Starting external issue analysis")

    # Build context
    context_parts = []
    if issue_title:
        context_parts.append(f"Issue Title: {issue_title}")
    if issue_labels:
        context_parts.append(f"Labels: {', '.join(issue_labels)}")

    additional_context = "\n".join(context_parts) if context_parts else None

    return await analyze_text_llm(
        content=issue_content,
        task_type="issue_analysis",
        additional_context=additional_context,
        timeout_seconds=timeout_seconds,
        model=model,
    )


async def analyze_github_issue_llm(
    issue_number: int,
    repository: str = "kesslerio/vibe-check-mcp",
    post_comment: bool = True,
    analysis_mode: str = "comprehensive",
    detail_level: str = "standard",
    timeout_seconds: int = 90,
    model: str = "sonnet",
) -> Dict[str, Any]:
    """
    GitHub issue vibe check with Claude CLI reasoning and optional comment posting.
    Docs: https://github.com/kesslerio/vibe-check-mcp/blob/main/data/tool_descriptions.json
    """
    logger.info(
        f"Starting external GitHub issue vibe check for {repository}#{issue_number}"
    )

    # Use the GitHub abstraction layer
    github_ops = get_default_github_operations()

    # Check authentication first
    auth_result = github_ops.check_authentication()
    if not auth_result.success:
        return {
            "status": "error",
            "error": "GitHub authentication not available",
            "solution": auth_result.error or "Check GitHub authentication",
        }

    try:
        # Fetch issue data using abstraction layer
        issue_result = github_ops.get_issue(repository, issue_number)
        if not issue_result.success:
            return {
                "status": "error",
                "error": f"Failed to fetch issue: {issue_result.error}",
                "issue_number": issue_number,
                "repository": repository,
            }

        issue = issue_result.data

        # ENHANCEMENT #152: Extract code references from issue content with improved validation
        code_context = ""
        referenced_files = []
        try:
            from vibe_check.core.code_reference_extractor import (
                CodeReferenceExtractor,
                ExtractionConfig,
            )

            # Use configurable extraction with review feedback improvements
            config = ExtractionConfig(
                max_context_lines=timeout_seconds // 10,  # Scale context with timeout
                max_files_per_issue=3,
                max_line_refs_per_file=2,
                enable_metrics_logging=True,
            )
            extractor = CodeReferenceExtractor(config)

            issue_text = f"{issue.title}\n\n{issue.body or ''}"
            references = extractor.extract_references(issue_text)

            # Get unique files, respecting limits
            unique_files = extractor.get_unique_files(references)
            file_lines = extractor.get_file_with_lines(references)

            if unique_files:
                logger.info(
                    f"Found {len(unique_files)} validated file references in issue #{issue_number}"
                )

                # Fetch actual code content for referenced files
                code_snippets = []
                for file_path in unique_files[: config.max_files_per_issue]:
                    try:
                        file_result = github_ops.get_file_contents(
                            repository, file_path
                        )
                        if file_result.success:
                            file_content = file_result.data.get("content", "")

                            # If specific lines are referenced, extract context around them
                            if file_path in file_lines:
                                line_numbers = file_lines[file_path]
                                for line_num in line_numbers[
                                    : config.max_line_refs_per_file
                                ]:
                                    context_lines = _extract_code_context(
                                        file_content, line_num, config.max_context_lines
                                    )
                                    if context_lines:
                                        code_snippets.append(
                                            f"""
**File: {file_path}** (lines around {line_num})
```
{context_lines}
```"""
                                        )
                            else:
                                # Show first 20 lines for context
                                lines = file_content.split("\n")[:20]
                                code_snippets.append(
                                    f"""
**File: {file_path}** (first 20 lines)
```
{chr(10).join(lines)}
```"""
                                )

                            referenced_files.append(file_path)
                        else:
                            logger.warning(
                                f"Could not fetch {file_path}: {file_result.error}"
                            )
                    except Exception as e:
                        logger.warning(f"Error fetching {file_path}: {e}")

                if code_snippets:
                    # Get function names for summary
                    function_names = [
                        ref.value for ref in references if ref.type == "function_name"
                    ]

                    code_context = f"""

## 📄 Referenced Code Analysis

{chr(10).join(code_snippets)}

**Code References Detected:**
- File paths: {', '.join(unique_files)}
- Function names: {', '.join(function_names)}
- Files with line references: {', '.join(file_lines.keys())}
"""
        except Exception as e:
            logger.warning(f"Enhanced code reference extraction failed: {e}")

        # Build comprehensive issue context with code
        issue_context = f"""# GitHub Issue Analysis
        
**Issue:** {issue.title}
**Repository:** {repository}
**Author:** {issue.user_login}
**State:** {issue.state}
**Labels:** {', '.join(issue.labels) if issue.labels else 'None'}

**Issue Content:**
{issue.body or 'No content provided'}
{code_context}
"""

        # Create vibe check prompt based on detail level
        detail_instructions = {
            "brief": "Provide a concise 3-section analysis with key points only.",
            "standard": "Provide a balanced analysis with practical guidance and clear recommendations.",
            "comprehensive": "Provide detailed analysis with extensive educational content, examples, and learning opportunities.",
        }

        detail_instruction = detail_instructions.get(
            detail_level, detail_instructions["standard"]
        )

        # Enhanced prompt with integration pattern detection
        integration_context = ""
        try:
            from vibe_check.tools.integration_pattern_analysis import (
                quick_technology_scan,
            )

            tech_scan = quick_technology_scan(issue_context)
            if tech_scan.get("status") == "technologies_detected":
                tech_list = [t["technology"] for t in tech_scan.get("technologies", [])]
                integration_context = f"""
**Integration Technologies Detected:** {', '.join(tech_list)}
**Integration Alert:** Check for official alternatives before custom development
"""
        except Exception:
            pass  # Continue without integration context if it fails

        # Check for doom loop patterns in issue content
        doom_loop_context = ""
        try:
            from vibe_check.tools.doom_loop_analysis import analyze_text_for_doom_loops

            doom_analysis = analyze_text_for_doom_loops(
                issue_context, tool_name="analyze_github_issue_llm"
            )
            if doom_analysis.get("status") == "doom_loop_detected":
                severity = doom_analysis.get("severity", "unknown")
                doom_loop_context = f"""
**PRODUCTIVITY ALERT:** {severity.upper()} doom loop patterns detected in issue discussion
**Pattern:** {doom_analysis.get("pattern_type", "").replace('_', ' ').title()}
**Intervention Needed:** Focus on concrete next steps over endless analysis
"""
        except Exception:
            pass  # Continue without doom loop context if it fails

        # Add code analysis guidance if we have code context
        code_analysis_guidance = ""
        if referenced_files:
            code_analysis_guidance = f"""

CODE-AWARE ANALYSIS: This issue references actual code files. Provide specific technical guidance:
- Analyze the actual code shown for the reported problems
- Give line-specific recommendations where applicable
- Identify root causes based on the actual implementation
- Suggest specific fixes rather than generic advice
- Files analyzed: {', '.join(referenced_files)}
"""

        vibe_prompt = f"""You are a friendly engineering coach providing a "vibe check" on this GitHub issue. Focus on preventing common engineering anti-patterns while encouraging good practices.

SPECIAL ATTENTION: This issue mentions integration technologies. Pay special attention to:
- Whether official solutions (SDKs, containers, APIs) are being considered
- Signs of custom development when standard approaches might work
- Integration complexity that could be simplified

PRODUCTIVITY FOCUS: If doom loop patterns are detected, emphasize:
- Moving from analysis to concrete action
- Setting time limits for decisions
- Implementing simplest working solution first
- Avoiding perfectionist paralysis

{code_analysis_guidance}

{detail_instruction}

{issue_context}
{integration_context}
{doom_loop_context}

Please provide a vibe check analysis in this format:

## 🎯 Vibe Check Summary
[One-sentence friendly assessment]

## 🔍 Engineering Guidance
- Research Phase: [Have we done our homework on existing solutions? Any official alternatives?]
- POC Needs: [Do we need to prove basic functionality first? Test standard approaches?]
- Complexity Check: [Is the proposed complexity justified? Could official solutions work?]
- Integration Check: [If integrating with third-party services, are we using official approaches?]
- Code Analysis: [If code was provided, what specific issues were found? Line-specific recommendations?]

## 💡 Friendly Recommendations
[3-5 practical, encouraging recommendations - prioritize checking official solutions for any detected technologies]

## 🎓 Learning Opportunities  
[2-3 educational suggestions based on patterns detected, include integration best practices if relevant]

Use friendly, coaching language that helps developers learn rather than intimidate. If integration technologies are detected, gently guide toward researching official solutions first."""

        # Run external Claude analysis
        result = await analyze_text_llm(
            content=vibe_prompt,
            task_type="issue_analysis",
            additional_context=f"Vibe check for GitHub issue {repository}#{issue_number}",
            timeout_seconds=timeout_seconds,
            model=model,
        )

        # Build response
        response = {
            "status": "vibe_check_complete",
            "issue_number": issue_number,
            "repository": repository,
            "analysis_mode": analysis_mode,
            "claude_analysis": result.output if result.success else None,
            "analysis_error": result.error if not result.success else None,
            "comment_posted": False,
            "github_implementation": issue_result.implementation,
            # ENHANCEMENT #152: Enhanced code-aware analysis metadata
            "code_analysis": {
                "files_analyzed": referenced_files,
                "references_extracted": (
                    len(references) if "references" in locals() else 0
                ),
                "unique_files_found": (
                    len(unique_files) if "unique_files" in locals() else 0
                ),
                "functions_detected": (
                    len([r for r in references if r.type == "function_name"])
                    if "references" in locals()
                    else 0
                ),
                "enhancement_active": len(referenced_files) > 0,
                "validation_enabled": True,
                "binary_filtering_enabled": True,
            },
        }

        # Post comment if requested and analysis succeeded
        if post_comment and result.success and result.output:
            comment_body = f"""## 🎯 Comprehensive Vibe Check

{result.output}

---
*🤖 This vibe check was lovingly crafted by [Vibe Check MCP](https://github.com/kesslerio/vibe-check-mcp) using the Claude Code SDK. Because your code deserves better than just "looks good to me" 🚀*"""

            comment_result = github_ops.post_issue_comment(
                repository, issue_number, comment_body
            )
            response["comment_posted"] = comment_result.success

            if comment_result.success and comment_result.data.get("comment_url"):
                response["comment_url"] = comment_result.data["comment_url"]
                response["user_message"] = (
                    f"✅ Analysis posted to GitHub: {comment_result.data['comment_url']}"
                )

            if not comment_result.success:
                response["comment_error"] = (
                    f"Failed to post comment: {comment_result.error}"
                )

        # Sanitize any GitHub API URLs to frontend URLs
        from vibe_check.tools.shared.github_helpers import (
            sanitize_github_urls_in_response,
        )

        return sanitize_github_urls_in_response(response)

    except Exception as e:
        logger.error(f"Error in GitHub issue vibe check: {e}")
        return {
            "status": "error",
            "error": str(e),
            "issue_number": issue_number,
            "repository": repository,
        }


async def analyze_github_pr_llm(
    pr_number: int,
    repository: str = "kesslerio/vibe-check-mcp",
    post_comment: bool = True,
    analysis_mode: str = "comprehensive",
    detail_level: str = "standard",
    timeout_seconds: int = 120,
    model: str = "sonnet",
) -> Dict[str, Any]:
    """
    GitHub PR vibe check with Claude CLI reasoning and optional review posting.
    Docs: https://github.com/kesslerio/vibe-check-mcp/blob/main/data/tool_descriptions.json
    """
    logger.info(f"Starting external GitHub PR vibe check for {repository}#{pr_number}")

    # Use the GitHub abstraction layer
    github_ops = get_default_github_operations()

    # Check authentication first
    auth_result = github_ops.check_authentication()
    if not auth_result.success:
        return {
            "status": "error",
            "error": "GitHub authentication not available",
            "solution": auth_result.error or "Check GitHub authentication",
        }

    try:
        # Fetch PR data using abstraction layer
        pr_result = github_ops.get_pull_request(repository, pr_number)
        if not pr_result.success:
            return {
                "status": "error",
                "error": f"Failed to fetch PR: {pr_result.error}",
                "pr_number": pr_number,
                "repository": repository,
            }

        pr = pr_result.data

        # PHASE 1 IMPLEMENTATION: Extract PR size data for intelligent filtering
        pr_size_data = {
            "number": pr.number,
            "title": pr.title,
            "additions": getattr(pr, "additions", 0),
            "deletions": getattr(pr, "deletions", 0),
            "changed_files": getattr(pr, "changed_files", 0),
        }

        # PHASE 1-4 IMPLEMENTATION: Complete analysis strategy with async processing
        from vibe_check.core.pr_filtering import (
            analyze_with_fallback,
            should_use_llm_analysis,
        )
        from vibe_check.tools.analyze_pr_nollm import analyze_pr_nollm
        from vibe_check.tools.async_analysis.integration import start_async_analysis
        from vibe_check.tools.async_analysis.config import DEFAULT_ASYNC_CONFIG

        # PHASE 4 CHECK: Determine if PR should use async processing
        async_config = DEFAULT_ASYNC_CONFIG
        if async_config.should_use_async_processing(pr_size_data):
            logger.info(
                f"PR {repository}#{pr_number} is massive - using async processing",
                extra={
                    "total_changes": pr_size_data.get("additions", 0)
                    + pr_size_data.get("deletions", 0),
                    "changed_files": pr_size_data.get("changed_files", 0),
                },
            )

            # Start async analysis
            async_result = await start_async_analysis(
                pr_number=pr_number, repository=repository, pr_data=pr_size_data
            )

            # Sanitize GitHub URLs and return
            from vibe_check.tools.shared.github_helpers import (
                sanitize_github_urls_in_response,
            )

            return sanitize_github_urls_in_response(async_result)

        async def llm_analysis():
            """Perform LLM analysis for smaller PRs."""
            # Get PR diff for analysis using the fixed abstraction layer
            diff_result = github_ops.get_pull_request_diff(repository, pr_number)
            if not diff_result.success:
                raise Exception(f"Failed to fetch PR diff: {diff_result.error}")

            pr_diff = diff_result.data

            # Check for existing implementations before suggesting improvements
            file_pattern_context = _check_common_file_patterns(pr_diff, repository)

            # Build comprehensive PR context
            pr_context = f"""# GitHub Pull Request Analysis
            
**PR:** {pr.title}
**Repository:** {repository}
**Author:** {pr.user_login}
**State:** {pr.state}
**Base:** {pr.base_ref} ← **Head:** {pr.head_ref}
**Labels:** {', '.join(pr.labels) if pr.labels else 'None'}

**PR Description:**
{pr.body or 'No description provided'}

{file_pattern_context}

**Code Changes:**
{pr_diff}
"""

            # Create vibe check prompt based on detail level
            detail_instructions = {
                "brief": "Provide a concise 3-section analysis with key points only.",
                "standard": "Provide a balanced analysis with practical guidance and clear recommendations.",
                "comprehensive": "Provide detailed analysis with extensive educational content, examples, and learning opportunities.",
            }

            detail_instruction = detail_instructions.get(
                detail_level, detail_instructions["standard"]
            )

            # Enhanced PR prompt with integration pattern detection
            pr_integration_context = ""
            try:
                from vibe_check.tools.integration_pattern_analysis import (
                    analyze_integration_patterns_fast,
                )

                integration_analysis = analyze_integration_patterns_fast(
                    pr_context, detail_level="brief"
                )
                if integration_analysis.get("technologies_detected"):
                    tech_list = [
                        t["technology"]
                        for t in integration_analysis.get("technologies_detected", [])
                    ]
                    warning_level = integration_analysis.get("warning_level", "none")
                    pr_integration_context = f"""
**INTEGRATION ANALYSIS:**
- Technologies Detected: {', '.join(tech_list)}
- Warning Level: {warning_level}
- Integration Alert: Verify official alternatives are considered
"""
            except Exception:
                pass  # Continue without integration context if it fails

            # Check for doom loop patterns in PR content
            pr_doom_loop_context = ""
            try:
                from vibe_check.tools.doom_loop_analysis import (
                    analyze_text_for_doom_loops,
                )

                doom_analysis = analyze_text_for_doom_loops(
                    pr_context, tool_name="analyze_github_pr_llm"
                )
                if doom_analysis.get("status") == "doom_loop_detected":
                    severity = doom_analysis.get("severity", "unknown")
                    pr_doom_loop_context = f"""
**PRODUCTIVITY ALERT:** {severity.upper()} analysis patterns detected in PR
**Pattern:** {doom_analysis.get("pattern_type", "").replace('_', ' ').title()}
**Focus:** Prioritize shipping working solution over perfect implementation
"""
            except Exception:
                pass  # Continue without doom loop context if it fails

            vibe_prompt = f"""You are a friendly engineering coach providing a "vibe check" on this GitHub pull request. Focus on preventing common engineering anti-patterns while encouraging good practices.

SPECIAL ATTENTION: Pay attention to integration patterns:
- Are official SDKs/containers being used instead of custom solutions?
- Is the development effort proportional to the integration complexity?
- Are there signs of reinventing existing solutions?

PRODUCTIVITY FOCUS: If analysis paralysis patterns are detected, emphasize:
- Shipping working solution over perfect implementation
- Iterative improvement over big-bang releases
- Real user feedback over theoretical optimization
- Time-boxed decisions and concrete milestones

{detail_instruction}

{pr_context}
{pr_integration_context}
{pr_doom_loop_context}

Please provide a vibe check analysis in this format:

## 🎯 PR Vibe Check Summary
[One-sentence friendly assessment of the overall PR quality]

## 🔍 Engineering Analysis
- Code Quality: [Structure, naming, organization, maintainability]
- Security & Performance: [Potential vulnerabilities, performance implications]
- Anti-Pattern Detection: [Infrastructure-without-implementation, integration over-engineering, complexity escalation]
- Integration Patterns: [If integrations present, are official solutions being used?]
- Testing & Documentation: [Test coverage, documentation updates needed]

## 💡 Friendly Recommendations
[3-5 practical, encouraging recommendations for improvement - include integration guidance if relevant]

## 🎓 Learning Opportunities  
[2-3 educational suggestions based on patterns detected, include integration best practices if applicable]

## ✅ Ready to Ship?
[Final recommendation: approve, request changes, or needs discussion]

Use friendly, coaching language that helps developers learn rather than intimidate. If integration technologies are detected, gently suggest verifying official alternatives."""

            # Run external Claude analysis
            result = await analyze_text_llm(
                content=vibe_prompt,
                task_type="pr_review",
                additional_context=f"Vibe check for GitHub PR {repository}#{pr_number}",
                timeout_seconds=timeout_seconds,
                model=model,
            )

            if result.success:
                return {
                    "status": "vibe_check_complete",
                    "pr_number": pr_number,
                    "repository": repository,
                    "analysis_mode": analysis_mode,
                    "claude_analysis": result.output,
                    "github_implementation": pr_result.implementation,
                }
            else:
                raise Exception(f"Claude analysis failed: {result.error}")

        def fast_analysis():
            """Perform fast analysis fallback."""
            return analyze_pr_nollm(
                pr_number=pr_number,
                repository=repository,
                analysis_mode="quick",
                detail_level=detail_level,
            )

        # PHASE 1 IMPLEMENTATION: Use intelligent analysis with fallback
        analysis_result = await analyze_with_fallback(
            pr_data=pr_size_data,
            llm_analyzer_func=llm_analysis,
            fast_analyzer_func=fast_analysis,
        )

        # Ensure we have the required fields for posting
        if "pr_number" not in analysis_result:
            analysis_result["pr_number"] = pr_number
        if "repository" not in analysis_result:
            analysis_result["repository"] = repository

        # Post review if requested and analysis succeeded
        if post_comment and analysis_result.get("claude_analysis"):
            review_body = f"""## 🎯 Comprehensive PR Vibe Check

{analysis_result['claude_analysis']}

---
*🤖 This vibe check was lovingly crafted by [Vibe Check MCP](https://github.com/kesslerio/vibe-check-mcp) using the Claude Code SDK. Because your code deserves better than just "looks good to me" 🚀*"""

            # For now, use create_and_submit_pull_request_review
            # TODO: Could enhance to use the abstraction layer when PR review methods are added
            try:
                from vibe_check.tools.shared.github_helpers import get_github_client

                client = get_github_client()
                if client:
                    repo = client.get_repo(repository)
                    pr_obj = repo.get_pull(pr_number)
                    review = pr_obj.create_review(body=review_body, event="COMMENT")
                    analysis_result["comment_posted"] = True

                    # Build PR review URL
                    review_url = f"https://github.com/{repository}/pull/{pr_number}#pullrequestreview-{review.id}"
                    analysis_result["comment_url"] = review_url
                    analysis_result["user_message"] = (
                        f"✅ Review posted to GitHub: {review_url}"
                    )
                else:
                    analysis_result["comment_error"] = "GitHub client not available"
            except Exception as e:
                analysis_result["comment_error"] = f"Failed to post review: {str(e)}"
        elif post_comment and not analysis_result.get("claude_analysis"):
            # Post a simpler comment for fast analysis mode
            if analysis_result.get("status") == "large_pr_detected":
                review_body = f"""## 🎯 Large PR Analysis

{analysis_result.get('message', 'Large PR detected - providing fast analysis')}

### 📊 Size Metrics
- Files changed: {analysis_result.get('size_metrics', {}).get('changed_files', 'unknown')}
- Total changes: {analysis_result.get('size_metrics', {}).get('total_changes', 'unknown')} lines

### 💡 Recommendations
{analysis_result.get('recommendation', 'Consider splitting into smaller PRs for detailed review')}

---
*🤖 Fast analysis by [Vibe Check MCP](https://github.com/kesslerio/vibe-check-mcp) - Large PRs get pattern detection to ensure reliable response 🚀*"""

                try:
                    from vibe_check.tools.shared.github_helpers import get_github_client

                    client = get_github_client()
                    if client:
                        repo = client.get_repo(repository)
                        pr_obj = repo.get_pull(pr_number)
                        review = pr_obj.create_review(body=review_body, event="COMMENT")
                        analysis_result["comment_posted"] = True

                        # Build PR review URL
                        review_url = f"https://github.com/{repository}/pull/{pr_number}#pullrequestreview-{review.id}"
                        analysis_result["comment_url"] = review_url
                        analysis_result["user_message"] = (
                            f"✅ Fast analysis posted to GitHub: {review_url}"
                        )
                except Exception as e:
                    analysis_result["comment_error"] = (
                        f"Failed to post review: {str(e)}"
                    )

        # Sanitize any GitHub API URLs to frontend URLs
        from vibe_check.tools.shared.github_helpers import (
            sanitize_github_urls_in_response,
        )

        return sanitize_github_urls_in_response(analysis_result)

    except Exception as e:
        # PHASE 1 IMPLEMENTATION: Ultimate graceful degradation
        logger.error(f"Error in GitHub PR vibe check: {e}")
        return {
            "status": "error_fallback",
            "error": str(e),
            "pr_number": pr_number,
            "repository": repository,
            "message": "Analysis encountered errors but system ensured response",
            "note": "This implements graceful degradation from Issue #101 - system never fails completely",
        }
