# cli.py
from __future__ import annotations

from .crm import send_crm_webhook
from .inventory import InventoryRAG
from .sales_brain import SalesBrain


def _strip_meta(memory: dict) -> dict:
    return {k: v for k, v in (memory or {}).items() if k != "_meta"}


def main():
    brain = SalesBrain()
    state = "GREETING"
    memory = {}  # later: CRM summary
    inventory = InventoryRAG.from_env()

    print("Sales Brain CLI. Type 'exit' to quit.\n")

    while True:
        user = input("You: ").strip()
        if user.lower() in ("exit", "quit"):
            payload = _strip_meta(memory)
            if payload:
                sent = send_crm_webhook(payload)
                if sent:
                    print("CRM webhook sent.")
            break

        rag_facts = inventory.build_rag_facts(memory, user) if inventory else None
        out = brain.run_turn(state, user, memory=memory, rag_facts=rag_facts)
        state = out.next_state

        # Update memory with extracted facts (simple merge)
        ex = out.extracted.to_dict()
        for k, v in ex.items():
            if v in (None, "", []):
                continue
            if k not in memory or memory.get(k) in (None, "", []):    
                memory[k] = v
        if out.meta:
            memory["_meta"] = out.meta

        print("\nAgent:", out.reply)
        print(f"[state={out.next_state} score={out.lead_score} missing={out.missing_fields} flags={out.safety_flags}]")
        print(f"[memory]={_strip_meta(memory)}\n")

if __name__ == "__main__":
    main()

