#!/usr/bin/env python3
from __future__ import annotations

import shutil
import sys
from datetime import datetime
from pathlib import Path

import chromadb

PROJECT_ROOT = Path(__file__).resolve().parents[1]
DB_PATH = PROJECT_ROOT / "workspace" / "chroma_db"
BACKUP_ROOT = PROJECT_ROOT / "backups"
COLLECTIONS = ("projects", "conversations")

TERMS = (
    "cyberbrain26vm_v1.0beta",
    "persistence test",
    "persistentní paměť byla ověřena",
    "test_release",
)


def is_stale(document: str | None) -> bool:
    text = (document or "").lower()
    return any(term in text for term in TERMS)


def load_matches(client: chromadb.PersistentClient) -> dict[str, list[dict]]:
    matches: dict[str, list[dict]] = {}

    for name in COLLECTIONS:
        try:
            collection = client.get_collection(name)
        except Exception as exc:
            print(f"[WARN] Kolekce '{name}' není dostupná: {exc}")
            matches[name] = []
            continue

        data = collection.get(include=["documents", "metadatas"])
        items = []

        for item_id, document, metadata in zip(
            data["ids"],
            data["documents"],
            data["metadatas"],
        ):
            if is_stale(document):
                items.append(
                    {
                        "id": item_id,
                        "metadata": metadata or {},
                        "preview": (document or "").replace("\n", " ")[:500],
                    }
                )

        matches[name] = items

    return matches


def print_matches(matches: dict[str, list[dict]]) -> int:
    total = 0

    print("\n=== Nalezené zastaralé testovací záznamy ===")
    for name, items in matches.items():
        print(f"\n[{name}] {len(items)} záznamů")
        for item in items:
            total += 1
            print(f"  ID: {item['id']}")
            print(f"  metadata: {item['metadata']}")
            print(f"  text: {item['preview']}")
            print()

    print(f"Celkem k odstranění: {total}")
    return total


def backup_database() -> Path:
    if not DB_PATH.is_dir():
        raise FileNotFoundError(f"ChromaDB neexistuje: {DB_PATH}")

    BACKUP_ROOT.mkdir(parents=True, exist_ok=True)
    timestamp = datetime.now().strftime("%Y%m%d-%H%M%S")
    destination = BACKUP_ROOT / f"chroma_db-before-stale-memory-cleanup-{timestamp}"

    print(f"\n[INFO] Vytvářím zálohu:\n  {destination}")
    shutil.copytree(DB_PATH, destination)
    print("[OK] Záloha vytvořena.")
    return destination


def delete_matches(client: chromadb.PersistentClient, matches: dict[str, list[dict]]) -> int:
    deleted = 0

    for name, items in matches.items():
        ids = [item["id"] for item in items]
        if not ids:
            print(f"[INFO] {name}: nic k odstranění.")
            continue

        collection = client.get_collection(name)
        collection.delete(ids=ids)
        deleted += len(ids)
        print(f"[OK] {name}: odstraněno {len(ids)} záznamů.")

    return deleted


def main() -> int:
    print("CyberBrain26 – cleanup zastaralé testovací paměti")
    print(f"[INFO] Projekt: {PROJECT_ROOT}")
    print(f"[INFO] ChromaDB: {DB_PATH}")

    if not DB_PATH.is_dir():
        print(f"[ERROR] Nenalezena ChromaDB: {DB_PATH}", file=sys.stderr)
        return 1

    client = chromadb.PersistentClient(path=str(DB_PATH))
    matches = load_matches(client)
    total = print_matches(matches)

    if total == 0:
        print("\n[OK] Žádné odpovídající zastaralé testovací záznamy nebyly nalezeny.")
        return 0

    backup_database()

    confirmation = input(
        "\nNapiš přesně DELETE pro smazání výše uvedených záznamů "
        "(cokoli jiného operaci zruší): "
    ).strip()

    if confirmation != "DELETE":
        print("[CANCELLED] Nic nebylo smazáno. Záloha zůstala vytvořená.")
        return 0

    deleted = delete_matches(client, matches)

    print("\n=== Ověření po smazání ===")
    remaining = load_matches(client)
    remaining_total = print_matches(remaining)

    if remaining_total:
        print(
            f"[WARN] Odstraněno {deleted}, ale zbývá {remaining_total} shod. "
            "Nic dalšího skript automaticky nemaže.",
            file=sys.stderr,
        )
        return 2

    print(f"\n[OK] Úspěch: odstraněno {deleted} zastaralých záznamů.")
    print("[NEXT] Restartuj CyberBrain26 / safe-oi, aby načetl nový stav paměti.")
    return 0


if __name__ == "__main__":
    raise SystemExit(main())
