import hashlib
from typing import List, Dict, Any

class MemorySynthesizer:
    """
    Synthesizes cross-swarm memory by extracting successful fixes 
    from chat histories.
    """
    def extract_learnings(self, chat_history: List[Any]) -> List[Dict[str, str]]:
        """
        Parses successful fixes from chat history into a list of dicts.
        Returns format: [{"hash": "xyz", "fix": "..."}]
        """
        learnings = []
        for entry in chat_history:
            if isinstance(entry, dict):
                # Ensure the entry is marked as a success or doesn't explicitly fail
                if entry.get("status") == "failure" or entry.get("success") is False:
                    continue
                
                fix = entry.get("fix")
                if not fix:
                    continue

                # Get or compute hash
                error_hash = entry.get("hash")
                if not error_hash:
                    error_msg = entry.get("error_msg") or entry.get("error")
                    if error_msg:
                        error_hash = hashlib.sha256(str(error_msg).encode('utf-8')).hexdigest()
                
                if error_hash:
                    learnings.append({"hash": error_hash, "fix": fix})
            
            elif isinstance(entry, str):
                # Simple parsing for string-based history
                # Expecting format like "Error: <error_msg> Fix: <fix_msg>"
                if "Error:" in entry and "Fix:" in entry:
                    try:
                        error_part = entry.split("Error:")[1].split("Fix:")[0].strip()
                        fix_part = entry.split("Fix:")[1].strip()
                        
                        if error_part and fix_part:
                            error_hash = hashlib.sha256(error_part.encode('utf-8')).hexdigest()
                            learnings.append({"hash": error_hash, "fix": fix_part})
                    except IndexError:
                        pass

        return learnings
