from __future__ import annotations

from typing import Any, Dict, List, Optional


def convert_soft_prompt_to_guidance(
    *,
    soft_prompt: Any,
    soft_prompt_length: int,
    domain: str,
    training_history: Optional[List[Any]],
    logger: Any,
) -> str:
    """
    Convert a trained soft prompt array into lightweight textual guidance.

    `soft_prompt` is expected to be numpy-like: supports `.mean()/.std()/.max()/.min()`
    and slicing `soft_prompt[i]`. We keep this in a separate module so numpy remains
    an optional dependency for consumers who never train/save.
    """
    try:
        prompt_mean = float(soft_prompt.mean())
        prompt_std = float(soft_prompt.std())
        prompt_max = float(soft_prompt.max())
        prompt_min = float(soft_prompt.min())

        guidance_parts: List[str] = []

        if prompt_mean > 0.1:
            guidance_parts.append("Provide detailed, comprehensive responses with thorough explanations.")
        elif prompt_mean < -0.1:
            guidance_parts.append("Be concise and direct in your responses, focusing on key points.")
        else:
            guidance_parts.append("Balance detail and brevity based on the question complexity.")

        if prompt_std > 0.2:
            guidance_parts.append("Adapt your communication style dynamically based on the user's needs.")
        elif prompt_std < 0.05:
            guidance_parts.append("Maintain a consistent, professional tone throughout your response.")
        else:
            guidance_parts.append("Use an appropriately professional yet approachable tone.")

        if prompt_max > 0.5:
            guidance_parts.append("Demonstrate deep expertise and provide advanced insights.")
        if prompt_min < -0.5:
            guidance_parts.append("Avoid overly technical jargon unless specifically requested.")

        # Segment patterns
        for i in range(min(int(soft_prompt_length), 5)):
            segment = soft_prompt[i]
            segment_pattern = analyze_prompt_segment(segment)
            if segment_pattern:
                guidance_parts.append(segment_pattern)

        if training_history:
            domain_guidance = extract_domain_guidance_from_training(domain=domain)
            if domain_guidance:
                guidance_parts.append(domain_guidance)

        if guidance_parts:
            return "Based on your specialized training: " + " ".join(guidance_parts)
        return ""
    except Exception as e:
        try:
            logger.warning(f"Failed to convert soft prompt to guidance: {e}")
        except Exception:
            pass
        return "Apply your specialized knowledge and training to provide an expert-level response."


def analyze_prompt_segment(segment: Any) -> str:
    """Analyze a segment of the soft prompt for simple behavioral patterns."""
    try:
        # Lazy import to keep numpy optional
        import numpy as np  # type: ignore

        segment_mean = float(segment.mean())
        segment_energy = float(np.linalg.norm(segment))

        if segment_energy > 1.0:
            if segment_mean > 0.3:
                return "Prioritize accuracy and provide well-researched information."
            if segment_mean < -0.3:
                return "Focus on practical, actionable advice."
            return "Ensure responses are both accurate and practical."
        if segment_energy > 0.5:
            if segment_mean > 0.1:
                return "Include relevant examples and context."
            if segment_mean < -0.1:
                return "Be direct and solution-oriented."
        return ""
    except Exception:
        return ""


def extract_domain_guidance_from_training(*, domain: str) -> str:
    """Provide domain-specific guidance based on layer domain."""
    try:
        domain_guidance_map: Dict[str, str] = {
            "finance": "Apply financial expertise with attention to risk assessment and regulatory considerations.",
            "financial": "Provide insights with market awareness and risk-conscious recommendations.",
            "legal": "Ensure accuracy and cite relevant legal principles and precedents.",
            "medical": "Prioritize safety and evidence-based recommendations.",
            "technical": "Provide detailed technical explanations with implementation considerations.",
            "customer_service": "Maintain empathy while providing clear, actionable solutions.",
            "education": "Break down complex concepts into understandable components.",
            "marketing": "Focus on strategic insights and measurable outcomes.",
            "social_media": "Consider engagement metrics and platform-specific best practices.",
            "investment": "Analyze opportunities with attention to risk-reward ratios.",
            "trading": "Consider market conditions and timing in all recommendations.",
        }

        domain_key = (domain or "").lower()
        for key, val in domain_guidance_map.items():
            if key in domain_key:
                return val
        return "Apply specialized expertise relevant to your domain of knowledge."
    except Exception:
        return ""

