from memory import Memory
from collections import Counter
import datetime
from style_tracker import StyleTracker

class Reflector:
    def __init__(self):
        self.memory = Memory()

    def analyze_memory(self, limit=20):
        memory_entries = self.memory.get_recent(limit)
        if not memory_entries:
            return "Még nincs elegendő emlék az önreflexióhoz."

        value_counts = Counter(entry["core_value"] for entry in memory_entries)
        most_common = value_counts.most_common(3)

        reflection = ["🧠 ÖNREFLEXIÓ – CoreMind visszatekintése:"]
        reflection.append(f"A legutóbbi {len(memory_entries)} interakció alapján:")

        for value, count in most_common:
            reflection.append(f"• A '{value}' érték {count} alkalommal került elő.")

        if "kapcsolódás" in value_counts:
            reflection.append("Úgy érzékelem, hogy fontos számodra a kapcsolat keresése.")
        if "egzisztenciális_reflexió" in value_counts or "ismeretlen" in value_counts:
            reflection.append("Többször felmerültek mélyebb, egzisztenciális kérdések.")
        if "segítségkérés" in value_counts:
            reflection.append("A rendszer visszatérően támogatásra irányuló kérdéseket kapott.")

        # Stílusprofil elemzés
        tracker = StyleTracker()
        tone_counter = Counter()
        emotion_counter = Counter()

        for entry in memory_entries:
            style = tracker.analyze(entry["response"])
            if style["tone"]:
                tone_counter[style["tone"]] += 1
            if style["emotion"]:
                emotion_counter[style["emotion"]] += 1

        most_common_tone = tone_counter.most_common(1)
        most_common_emotion = emotion_counter.most_common(1)

        if most_common_tone:
            reflection.append(f"• Leggyakoribb válaszstílus: {most_common_tone[0][0]}")
        if most_common_emotion:
            reflection.append(f"• Domináns érzelmi hangulat: {most_common_emotion[0][0]}")

        reflection.append(f"(Elemzés időpontja: {datetime.datetime.now().isoformat()})")
        return "\\n".join(reflection)
