from __future__ import annotations

import re
import time

from armorer.core.memory_schema import DurableMemoryRecord, MemoryKind
from armorer.core.memory_store import list_memory_records, upsert_memory_record


def classify_task_type(prompt: str) -> str:
    text = str(prompt or "").strip().lower()
    if not text:
        return "general"
    if any(token in text for token in ("url", "dashboard", "endpoint", "port", "link", "access")):
        return "runtime_access"
    if any(token in text for token in ("setup", "configure", "pair", "bind")):
        return "setup"
    if any(token in text for token in ("debug", "fix", "why", "repair", "investigate")):
        return "repair"
    return "general"


def extract_app_alias(prompt: str, installed_agents: list[dict]) -> str:
    text = str(prompt or "").strip().lower()
    for item in installed_agents:
        if not isinstance(item, dict):
            continue
        for candidate in (str(item.get("alias") or "").strip(), str(item.get("agent_id") or "").strip()):
            if candidate and candidate.lower() in text:
                return candidate.lower()
    return ""


def recall_relevant_memory(*, prompt: str, installed_agents: list[dict]) -> list[dict]:
    task_type = classify_task_type(prompt)
    app_alias = extract_app_alias(prompt, installed_agents)
    relevant_tags = {task_type}
    if app_alias:
        relevant_tags.add(app_alias)
    results: list[dict] = []
    for record in list_memory_records():
        tags = {str(tag).strip().lower() for tag in record.tags}
        if task_type != "general" and task_type not in tags:
            continue
        if app_alias and app_alias not in tags and record.scope not in {"global", app_alias}:
            continue
        results.append(record.model_dump(mode="json"))
    return results[:10]


def promote_runtime_snapshot_facts(*, snapshot: dict, prompt: str) -> list[DurableMemoryRecord]:
    created: list[DurableMemoryRecord] = []
    now = time.time()
    task_type = classify_task_type(prompt)
    urls = snapshot.get("urls", {}) if isinstance(snapshot, dict) else {}
    for item in urls.get("items", []) or []:
        if not isinstance(item, dict):
            continue
        url = str(item.get("url") or "").strip()
        label = str(item.get("label") or "").strip()
        if not url or not label:
            continue
        normalized_subject = re.sub(r"\s+", "_", label.strip().lower())
        tags = [task_type, "runtime_access"]
        if "openclaw" in normalized_subject:
            tags.append("openclaw")
        record = DurableMemoryRecord(
            kind=MemoryKind.RUNTIME_FACT,
            subject=f"url:{normalized_subject}",
            value={
                "label": label,
                "url": url,
                "access": str(item.get("access") or "").strip(),
                "ready": bool(item.get("ready")),
                "note": str(item.get("note") or "").strip(),
            },
            source="runtime_snapshot",
            verified=True,
            created_at=now,
            expires_at=now + 86400,
            scope="global",
            tags=tags,
        )
        created.append(upsert_memory_record(record))
    return created
