"""
neurocli memory — persistent agent memory across sessions
"""
import json
from datetime import datetime
from .config import MEMORY_FILE, ensure_dirs


def load_memory() -> dict:
    ensure_dirs()
    if MEMORY_FILE.exists():
        with open(MEMORY_FILE) as f:
            return json.load(f)
    return {
        "facts": [],           # general facts about user/project
        "patterns": [],        # coding patterns observed
        "past_bugs": [],       # bugs fixed with solutions
        "preferences": {},     # language, libs, style prefs
        "projects": {},        # per-project context
    }


def save_memory(mem: dict):
    ensure_dirs()
    with open(MEMORY_FILE, "w") as f:
        json.dump(mem, f, indent=2)


def remember(key: str, value: str, project: str = None):
    mem = load_memory()
    entry = {"value": value, "time": datetime.now().isoformat()}
    if project:
        if project not in mem["projects"]:
            mem["projects"][project] = []
        mem["projects"][project].append(entry)
    else:
        mem["facts"].append({"key": key, "value": value, "time": entry["time"]})
    save_memory(mem)


def add_bug_fix(description: str, fix: str, file: str):
    mem = load_memory()
    mem["past_bugs"].append({
        "description": description,
        "fix": fix,
        "file": file,
        "time": datetime.now().isoformat()
    })
    # keep last 50 bugs
    mem["past_bugs"] = mem["past_bugs"][-50:]
    save_memory(mem)


def get_memory_context(project: str = None) -> str:
    """Return memory as a string to inject into AI system prompt."""
    mem = load_memory()
    lines = ["=== NEUROCLI MEMORY ==="]

    if mem["facts"]:
        lines.append("\nGeneral facts:")
        for f in mem["facts"][-10:]:
            lines.append(f"  - [{f['key']}] {f['value']}")

    if mem["preferences"]:
        lines.append("\nUser preferences:")
        for k, v in mem["preferences"].items():
            lines.append(f"  - {k}: {v}")

    if mem["past_bugs"]:
        lines.append("\nRecent bug fixes (learn from these):")
        for b in mem["past_bugs"][-5:]:
            lines.append(f"  - In {b['file']}: {b['description']} → {b['fix']}")

    if project and project in mem.get("projects", {}):
        lines.append(f"\nProject context ({project}):")
        for entry in mem["projects"][project][-5:]:
            lines.append(f"  - {entry['value']}")

    lines.append("=== END MEMORY ===")
    return "\n".join(lines)


def set_preference(key: str, value: str):
    mem = load_memory()
    mem["preferences"][key] = value
    save_memory(mem)


def get_all_memory() -> dict:
    return load_memory()
