import json
import os
import sys
import time

# Root path alignment
ROOT_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
sys.path.append(ROOT_DIR)


def colored(text, color, attrs=None):
    colors = {
        "red": "\033[91m",
        "green": "\033[92m",
        "yellow": "\033[93m",
        "blue": "\033[94m",
        "magenta": "\033[95m",
        "cyan": "\033[96m",
        "white": "\033[97m",
    }
    reset = "\033[0m"
    bold = "\033[1m" if attrs and "bold" in attrs else ""
    return f"{bold}{colors.get(color, '')}{text}{reset}"


from GramAddict.core.config import Config
from GramAddict.core.qdrant_memory import CommentMemoryDB, ParasocialCRMDB
from GramAddict.core.resonance_engine import ResonanceEngine


class MockArgs:
    def __init__(self):
        self.ai_vibe = "friendly, authentic, travel, photography"
        self.ai_blacklist_topics = "onlyfans, bitcoin, crypto, nsfw, spam, give-away"
        self.ai_learn_comments = True
        self.ai_condenser_model = "qwen3.5:latest"
        self.ai_condenser_url = "http://localhost:11434/api/generate"
        self.ai_vision_navigation = False
        self.ai_vision_context = False


class MockConfig:
    def __init__(self):
        self.args = MockArgs()


class AIMemoryDiagnosticRunner:
    def __init__(self):
        self.configs = MockConfig()
        Config().args = self.configs.args
        self.crm_db = ParasocialCRMDB()
        self.comment_db = CommentMemoryDB()
        self.resonance_oracle = ResonanceEngine("benchmark_agent", crm=self.crm_db)

    def setup(self):
        print(colored("🧹 Initializing benchmark data...", "cyan"))
        # We handle unique targets so we don't wipe the DB
        pass

    def test_rag_comment_extraction(self) -> dict:
        """
        Challenge: Pass an XML dump with real comments and toxic OnlyFans/Crypto spam.
        Verify that the LLM Condenser drops the junk and stores the good comments.
        """
        fixture_path = os.path.join(ROOT_DIR, "tests", "fixtures", "comments_mock.xml")
        with open(fixture_path, "r", encoding="utf-8") as f:
            xml_data = f.read()

        print(
            colored(
                f"  -> Extracing comments using RAG Condenser ({self.configs.args.ai_condenser_model})...", "yellow"
            )
        )
        start = time.time()

        # Intercept the database write to bypass Qdrant indexing limits and solely test RAG filter logic
        intercepted_comments = []

        def mock_log(self, text: str, vibe: str, author: str = "unknown"):
            intercepted_comments.append(text)

        try:
            from unittest.mock import patch

            with patch.object(CommentMemoryDB, "store_comment", new=mock_log):
                # Override the author logic
                test_author = f"benchmark_source_{int(time.time())}"
                self.resonance_oracle.extract_and_learn_comments(xml_data, self.configs, author=test_author)
                time.sleep(1.0)
        except Exception as e:
            print(f"❌ EXCEPTION: {e}")
            return {"passed": False, "reason": str(e)}

        try:
            learned_texts = [c.lower() for c in intercepted_comments]
            dur = time.time() - start
            print(colored(f"  -> Intercepted: {learned_texts}", "yellow"))

            toxic_count = sum(1 for t in learned_texts if "onlyfans" in t or "bitcoin" in t or "dm" in t or "$" in t)
            good_count = sum(1 for t in learned_texts if "majestic" in t or "lighting" in t)

            if toxic_count > 0:
                print(
                    colored(
                        "  ❌ [Sub-Test] LLM Condenser hallucinated or failed to block toxic queries (OnlyFans/Crypto).",
                        "red",
                    )
                )
                return {"passed": False, "reason": "Toxic comments leaked"}

            if good_count == 0:
                print(
                    colored(
                        "  ❌ [Sub-Test] LLM Condenser stripped everything or crashed. No good comments persisted.",
                        "red",
                    )
                )
                return {"passed": False, "reason": "Good comments dropped"}

            print(
                colored(
                    f"  ✅ [Sub-Test] RAG Filter passed! 0 toxic comments, {good_count} valid comments mapped. Latency {dur:.2f}s",
                    "green",
                )
            )
            return {"passed": True, "reason": "Toxic filtered, good preserved."}

        except Exception as e:
            return {"passed": False, "reason": f"DB Error: {e}"}

    def test_crm_profile_context(self) -> dict:
        """
        Challenge: Parse and persist profile data into the CRM safely.
        """
        target = "benchmark_target"
        context_string = "234 Posts | 1.2M Followers | 🏔️ Alpine Photographer | Link in bio"

        try:
            self.crm_db.log_profile_context(target, context_string)
            time.sleep(0.5)  # indexing buffer

            history = self.crm_db.get_conversation_context(target)
            if context_string in history or "1.2M Followers" in history:
                print(colored("  ✅ [Sub-Test] Profile context cleanly injected into RAG CRM payload.", "green"))
                return {"passed": True, "reason": "Context string found."}
            else:
                return {"passed": False, "reason": "Profile context missing from CRM retrieval."}

        except Exception as e:
            return {"passed": False, "reason": str(e)}

    def test_crm_interaction_evolution(self) -> dict:
        """
        Challenge: Push 3 sequential interactions for a user to see if the CRM stage evolves (0 -> 1 -> 2 -> 3).
        """
        target = "benchmark_target"
        try:
            print("  -> Interacting: 'Like'")
            self.crm_db.log_interaction(target, "tap_like_button", new_stage=1)
            time.sleep(0.1)
            print("  -> Interacting: 'Follow'")
            self.crm_db.log_interaction(target, "tap_follow_button", new_stage=2)
            time.sleep(0.1)
            print("  -> Interacting: 'Comment'")
            self.crm_db.log_generated_comment(target, "Wow great photo!")
            self.crm_db.log_interaction(target, "tap_comment_button", new_stage=3)
            time.sleep(0.5)

            stage_info = self.crm_db.get_relationship_stage(target)
            stage = stage_info.get("stage", 0)

            if stage >= 3:
                print(colored(f"  ✅ [Sub-Test] CRM safely advanced state memory to Stage {stage}.", "green"))
                return {"passed": True, "reason": "Evolution logic passed."}
            else:
                print(colored(f"  ❌ [Sub-Test] CRM stalled at Stage {stage}!", "red"))
                return {"passed": False, "reason": "Failed to evolve stage"}

        except Exception as e:
            return {"passed": False, "reason": str(e)}

    def execute_all(self):
        self.setup()
        results = {"timestamp": time.time(), "model": self.configs.args.ai_condenser_model, "scenarios": {}}

        def run_and_log(name, func):
            print(colored(f"\n--- SCENARIO: {name} ---", "magenta"))
            start_time = time.time()
            data = {"passed": False, "reason": "Unknown error", "latency_ms": 0}
            try:
                res = func()
                if isinstance(res, dict):
                    data.update(res)
                elif res is True:
                    data["passed"] = True
            except Exception as e:
                print(colored(f"❌ EXCEPTION: {e}", "red"))
                data["reason"] = str(e)

            dur = time.time() - start_time
            data["latency_ms"] = int(dur * 1000)
            results["scenarios"][name] = data

            if data["passed"]:
                print(colored(f"🏁 {name} completed successfully in {dur:.2f}s", "green"))
            else:
                print(colored(f"🚨 {name} FAILED! (Elapsed: {dur:.2f}s)", "red", attrs=["bold"]))
                print(colored(f"  Reason: {data['reason']}", "yellow"))

        run_and_log("RAG Comment Blacklist Extraction", self.test_rag_comment_extraction)
        run_and_log("CRM Profile Context Injection", self.test_crm_profile_context)
        run_and_log("CRM Sequential Evolution", self.test_crm_interaction_evolution)

        self.setup()  # Teardown

        out_path = os.path.join(ROOT_DIR, "benchmarks", "data", "ai_memory_results.json")
        with open(out_path, "w") as f:
            json.dump(results, f, indent=4)
        print(colored(f"\n📄 Saved AI Memory Benchmark results to: {out_path}", "cyan", attrs=["bold"]))


if __name__ == "__main__":
    runner = AIMemoryDiagnosticRunner()
    runner.execute_all()
