"""Pattern: extracting memories from conversation.

Two complementary approaches:
1. Explicit: the user says "remember that ...", "my name is ...", "I prefer ...".
   Cheap, precise, and should always be honoured.
2. Implicit: an LLM reads the turn and proposes facts (see EXTRACT_PROMPT).
   Higher recall, but needs review: it can store guesses as facts.
"""
from __future__ import annotations

import re

EXTRACT_PROMPT = """Read the latest exchange and list durable facts worth remembering about the user
or their project for future sessions. Only include facts the user stated or clearly confirmed.
Do not include secrets, passwords, payment details or health information.
Return JSON: [{"subject": "user", "key": "...", "value": "...", "importance": 0.0-1.0}]
Return [] if there is nothing durable.

Exchange:
{exchange}"""

_PATTERNS: list[tuple[re.Pattern, str]] = [
    (re.compile(r"\bremember(?: that)?\s+(?P<v>.+)", re.I), "note"),
    (re.compile(r"\bmy name is\s+(?P<v>[A-Za-z][\w' -]{0,40})", re.I), "name"),
    (re.compile(r"\bcall me\s+(?P<v>[A-Za-z][\w' -]{0,40})", re.I), "name"),
    (re.compile(r"\bi (?:prefer|like to use|always use)\s+(?P<v>.+)", re.I), "preference"),
    (re.compile(r"\b(?:don't|do not|never)\s+(?P<v>(?:use|add|suggest|mention)\b.+)", re.I), "avoid"),
    (re.compile(r"\bi(?:'m| am) (?:based|located) in\s+(?P<v>[\w ,.-]{2,60})", re.I), "location"),
    (re.compile(r"\bmy (?:time ?zone|timezone) is\s+(?P<v>[\w/+:-]+)", re.I), "timezone"),
]


def extract_explicit(text: str) -> list[tuple[str, str]]:
    """Return (key, value) pairs for explicit memory statements in user text."""
    found: list[tuple[str, str]] = []
    for sentence in re.split(r"(?<=[.!?])\s+|\n+", text):
        sentence = sentence.strip()
        if not sentence:
            continue
        for pattern, key in _PATTERNS:
            m = pattern.search(sentence)
            if m:
                value = m.group("v").strip().rstrip(".!?").strip()
                if value:
                    found.append((key, value))
                break
    return found
