"""Permission advisor that uses web search to suggest fixes.

When a tool fails with a permission error, this module searches for
API documentation and suggests how to fix the issue.
"""

from __future__ import annotations

from promethian.core.error_analyzer import ErrorAnalysis, ErrorCategory
from promethian.utils.claude import ClaudeClient


# Known API documentation URLs for common permission issues
API_DOCS = {
    "OpenAI": {
        "permissions_url": "https://platform.openai.com/docs/api-reference/authentication",
        "dashboard_url": "https://platform.openai.com/api-keys",
        "common_issues": [
            "API key not set or invalid",
            "API key doesn't have required model access",
            "Usage limits exceeded for your plan",
        ],
    },
    "Anthropic": {
        "permissions_url": "https://docs.anthropic.com/claude/reference/getting-started-with-the-api",
        "dashboard_url": "https://console.anthropic.com/settings/keys",
        "common_issues": [
            "API key not set or invalid",
            "Key doesn't have access to requested model",
        ],
    },
    "Stripe": {
        "permissions_url": "https://stripe.com/docs/keys",
        "dashboard_url": "https://dashboard.stripe.com/apikeys",
        "common_issues": [
            "Using test key with live endpoints (or vice versa)",
            "Restricted key missing required permissions",
            "API version mismatch",
        ],
    },
    "GitHub": {
        "permissions_url": "https://docs.github.com/en/authentication/keeping-your-account-and-data-secure/managing-your-personal-access-tokens",
        "dashboard_url": "https://github.com/settings/tokens",
        "common_issues": [
            "Token expired or revoked",
            "Token missing required scopes (repo, admin, etc.)",
            "Fine-grained token without required permissions",
        ],
    },
    "AWS": {
        "permissions_url": "https://docs.aws.amazon.com/IAM/latest/UserGuide/access_policies.html",
        "dashboard_url": "https://console.aws.amazon.com/iam/",
        "common_issues": [
            "IAM policy doesn't grant required actions",
            "Resource-based policy blocking access",
            "Credentials expired or invalid",
        ],
    },
    "Google Cloud": {
        "permissions_url": "https://cloud.google.com/iam/docs/overview",
        "dashboard_url": "https://console.cloud.google.com/iam-admin/",
        "common_issues": [
            "Service account missing required roles",
            "API not enabled for the project",
            "Credentials file not found or invalid",
        ],
    },
}


class PermissionAdvisor:
    """
    Advises on permission errors using API docs and web search.

    When a tool fails with a permission error, this advisor:
    1. Identifies the API from the error
    2. Looks up known documentation
    3. Optionally searches the web for specific issues
    4. Synthesizes a helpful suggestion
    """

    def __init__(self, claude: ClaudeClient | None = None):
        self.claude = claude

    def get_quick_advice(self, analysis: ErrorAnalysis) -> str:
        """
        Get quick advice without web search.

        Uses known API documentation and common issues.

        Args:
            analysis: The error analysis

        Returns:
            Advice string
        """
        if not analysis.is_permission_error:
            return analysis.suggested_action or "Check the error message for details."

        lines = []

        if analysis.api_name:
            lines.append(f"Permission error from {analysis.api_name} API.")

            if analysis.api_name in API_DOCS:
                docs = API_DOCS[analysis.api_name]

                lines.append(f"\nCommon causes:")
                for issue in docs.get("common_issues", []):
                    lines.append(f"  - {issue}")

                lines.append(f"\nTo fix:")
                lines.append(f"  1. Check your API key: {analysis.env_var_hint}")
                lines.append(f"  2. Verify permissions at: {docs['dashboard_url']}")
                lines.append(f"  3. Review docs: {docs['permissions_url']}")
        else:
            lines.append("Permission error detected.")
            lines.append("\nTo fix:")
            lines.append("  1. Verify your API credentials are set correctly")
            lines.append("  2. Check that the key has required permissions")
            lines.append("  3. Ensure the key hasn't expired")

        if analysis.error_message:
            lines.append(f"\nOriginal error: {analysis.error_message[:200]}")

        return "\n".join(lines)

    async def get_detailed_advice(
        self,
        analysis: ErrorAnalysis,
        tool_name: str | None = None,
        web_search_results: list[dict] | None = None,
    ) -> str:
        """
        Get detailed advice using Claude to synthesize information.

        Args:
            analysis: The error analysis
            tool_name: Optional name of the tool that failed
            web_search_results: Optional pre-fetched search results

        Returns:
            Detailed advice string
        """
        if not self.claude:
            return self.get_quick_advice(analysis)

        # Build context for Claude
        context_parts = [
            f"A tool execution failed with a permission error.",
            f"Tool: {tool_name or 'Unknown'}",
            f"Error: {analysis.error_message}",
            f"Error category: {analysis.category.value}",
        ]

        if analysis.api_name:
            context_parts.append(f"API: {analysis.api_name}")
            context_parts.append(f"Environment variable: {analysis.env_var_hint}")

            if analysis.api_name in API_DOCS:
                docs = API_DOCS[analysis.api_name]
                context_parts.append(f"Documentation: {docs['permissions_url']}")
                context_parts.append(f"Dashboard: {docs['dashboard_url']}")
                context_parts.append(f"Common issues: {', '.join(docs['common_issues'])}")

        if web_search_results:
            context_parts.append("\nRelevant web search results:")
            for result in web_search_results[:3]:
                context_parts.append(f"- {result.get('title', '')}: {result.get('snippet', '')}")

        prompt = f"""Based on this permission error, provide specific, actionable advice:

{chr(10).join(context_parts)}

Provide:
1. Most likely cause of this specific error
2. Step-by-step fix instructions
3. How to verify the fix worked

Be concise and specific. Focus on the most likely solution first."""

        try:
            response = await self.claude.complete(
                prompt=prompt,
                max_tokens=500,
            )
            return response
        except Exception:
            return self.get_quick_advice(analysis)

    def format_advice_for_user(
        self,
        analysis: ErrorAnalysis,
        advice: str,
    ) -> str:
        """
        Format advice for display to the user.

        Args:
            analysis: The error analysis
            advice: The advice text

        Returns:
            Formatted string for display
        """
        category_emoji = {
            ErrorCategory.PERMISSION: "🔐",
            ErrorCategory.RATE_LIMIT: "⏱️",
            ErrorCategory.NETWORK: "🌐",
            ErrorCategory.NOT_FOUND: "🔍",
            ErrorCategory.SERVER: "💥",
            ErrorCategory.UNKNOWN: "❓",
        }

        emoji = category_emoji.get(analysis.category, "❓")
        category_name = analysis.category.value.replace("_", " ").title()

        lines = [
            f"{emoji} {category_name} Error",
            "",
        ]

        if analysis.api_name:
            lines.append(f"API: {analysis.api_name}")

        lines.append("")
        lines.append(advice)

        return "\n".join(lines)
