"""
Smart Suggestions
Analyzes usage and provides actionable tips.
"""
from typing import Dict, Any, List
from .usage_tracker import UsageTracker
from .patterns import PatternDetector
from .model_perf import ModelPerformance
from .preferences import Preferences

class SuggestionEngine:
    def __init__(self, tracker: UsageTracker, patterns: PatternDetector, perf: ModelPerformance, prefs: Preferences):
        self.tracker = tracker
        self.patterns = patterns
        self.perf = perf
        self.prefs = prefs

    def get_hints(self, context: Dict[str, Any] = None) -> List[str]:
        hints = []
        top_models = self.tracker.top_models(days=7, limit=1)
        if top_models and top_models[0]["count"] > 10:
            m = top_models[0]["model"]
            hints.append(f"You use {m} a lot. Try gemini-pro for variety.")
            
        strats = self.tracker.top_strategies(days=7)
        if strats and strats[0]["strategy"] == "single":
            hints.append("You mostly use single models. Try the 'debate' strategy for complex questions.")
            
        if not hints:
            hints.append("Explore the marketplace for new capabilities: /marketplace")
            
        return hints[:3]

    def suggest_strategy(self, prompt: str) -> str:
        p = prompt.lower()
        if "compare" in p or "vs" in p:
            return "debate"
        if "write" in p or "draft" in p:
            return "refine"
        if "analyze" in p or "research" in p:
            return "fan_out"
        return "sequential"

    def suggest_model(self, prompt: str) -> str:
        p = prompt.lower()
        if "code" in p or "bug" in p or "function" in p:
            return self.perf.recommend_model("code")
        return self.perf.recommend_model()

    def suggest_chain(self, prompt: str) -> Dict[str, Any]:
        strat = self.suggest_strategy(prompt)
        model = self.suggest_model(prompt)
        return {
            "strategy": strat,
            "models": [model, "gemini"] if strat in ("debate", "refine") else [model],
            "temperature": 0.7,
            "rationale": f"Based on your prompt, {strat} with {model} seems optimal."
        }

    def improvement_tips(self) -> List[str]:
        tips = []
        alerts = self.perf.degradation_alerts()
        for a in alerts:
            tips.append(f"{a['model']} latency has increased by {a['change_pct']:.1f}% recently.")
            
        sw_rate = self.patterns.model_switching_rate(days=7)
        if sw_rate > 0.5:
            tips.append("You switch models frequently. Consider setting up a default Fan-Out chain.")
            
        return tips

    def model_alternatives(self, model: str) -> List[Dict[str, Any]]:
        scored = self.perf.rank_models(days=14)
        target_score = next((m["score"] for m in scored if m["model"] == model), 0.5)
        
        alts = []
        for m in scored:
            if m["model"] != model and m["score"] >= target_score - 0.1:
                alts.append({
                    "model": m["model"],
                    "reason": "Similar or better performance",
                    "score_diff": m["score"] - target_score
                })
        return alts[:3]

    def workflow_suggestions(self) -> List[Dict[str, Any]]:
        seqs = self.patterns.workflow_sequences(min_length=3)
        suggs = []
        for i, seq in enumerate(seqs):
            suggs.append({
                "name": f"Workflow {i+1}",
                "steps": seq,
                "frequency": "high",
                "suggestion": f"You often use {' -> '.join(seq)}. Save this as a template!"
            })
        return suggs

    def cost_saving_tips(self) -> List[str]:
        tips = []
        top = self.tracker.top_models()
        if any("opus" in m["model"] for m in top):
            tips.append("Switch summarization from claude-opus to claude-haiku — much cheaper, similar quality.")
        if any("gpt-4o" in m["model"] for m in top) and "gpt-4o-mini" not in [m["model"] for m in top]:
            tips.append("Try gpt-4o-mini for simple tasks to save tokens.")
        return tips

    def underused_features(self) -> List[str]:
        features = []
        strats = [s["strategy"] for s in self.tracker.top_strategies(days=30)]
        if "debate" not in strats:
            features.append("You haven't used debate strategy yet — great for getting balanced perspectives.")
        if "fan_out" not in strats:
            features.append("Try fan-out strategy to run multiple models in parallel.")
        return features

    def daily_digest(self) -> Dict[str, Any]:
        daily = self.tracker.daily_trend(days=1)
        today = daily[-1] if daily else {"count": 0}
        top = self.tracker.top_models(days=1, limit=1)
        hints = self.get_hints()
        
        return {
            "date": "today",
            "interactions": today["count"],
            "top_model": top[0]["model"] if top else "none",
            "suggestion_of_the_day": hints[0] if hints else "Keep up the good work!",
            "performance_trend": self.patterns.session_length_trend()["trend"]
        }
