"""AiFastDb Quick Start Example.

Demonstrates the core database, social graph, document store,
embedding engine, and pandas integration in one script.
"""

import tempfile
import os


def demo_core_database():
    """Core AiFastDb: remember, get, recall, forget."""
    from aifastdb import AiFastDb

    print("\n=== Core Database ===")
    with tempfile.TemporaryDirectory() as tmpdir:
        with AiFastDb(os.path.join(tmpdir, "db")) as db:
            # Store records
            db.remember("doc1", "The quick brown fox jumps over the lazy dog", tags=["classic"])
            db.remember("doc2", "Machine learning is transforming industries", tags=["tech"])
            db.remember("doc3", "Paris is the capital of France", tags=["geography"])

            # Retrieve
            doc = db.get("doc1")
            print(f"  Retrieved: {doc['content'][:40]}...")

            # Count
            print(f"  Documents: {len(db)}")

            # Delete
            db.forget("doc3")
            print(f"  After delete: {len(db)} documents")


def demo_social_graph():
    """SocialGraphV2: persons, friends, path finding."""
    from aifastdb import SocialGraphV2

    print("\n=== Social Graph ===")
    with tempfile.TemporaryDirectory() as tmpdir:
        with SocialGraphV2(os.path.join(tmpdir, "social")) as sg:
            # Add persons
            alice = sg.add_person({"name": "Alice", "age": 30})
            bob = sg.add_person({"name": "Bob", "age": 28})
            carol = sg.add_person({"name": "Carol", "age": 32})

            # Friendships
            sg.add_friend(alice["id"], bob["id"])
            sg.add_friend(bob["id"], carol["id"])

            friends = sg.get_friends(bob["id"])
            print(f"  Bob's friends: {[f.get('name', f.get('id')) for f in friends]}")

            # Path finding
            path = sg.find_path(alice["id"], carol["id"])
            if path:
                print(f"  Alice→Carol path: {path['hops']} hops")

            # Stats
            stats = sg.get_graph_stats()
            print(f"  Graph: {stats.get('entity_count', 0)} entities, {stats.get('relation_count', 0)} relations")


def demo_document_store():
    """DocumentStore: put, get, query by tag."""
    from aifastdb import DocumentStore

    print("\n=== Document Store ===")
    with tempfile.TemporaryDirectory() as tmpdir:
        with DocumentStore(os.path.join(tmpdir, "docs.jsonl")) as store:
            store.put("n1", "Buy groceries", doc_type="note", tags=["personal", "todo"])
            store.put("n2", "Sprint planning", doc_type="note", tags=["work"])
            store.put("n3", "Learn Rust", doc_type="note", tags=["personal", "tech"])

            print(f"  Total: {len(store)} documents")
            personal = store.find_by_tag("personal")
            print(f"  Personal: {len(personal)} documents")


def demo_embedding():
    """EmbeddingEngine: embed, numpy, batch, cosine similarity."""
    from aifastdb import EmbeddingEngine
    import numpy as np

    print("\n=== Embedding Engine ===")
    engine = EmbeddingEngine()  # dummy 384d

    vec = engine.embed("Hello world")
    print(f"  embed() → list[float], len={len(vec)}")

    arr = engine.embed_numpy("Hello world")
    print(f"  embed_numpy() → ndarray, shape={arr.shape}, dtype={arr.dtype}")

    batch = engine.embed_batch(["Hello", "World"])
    print(f"  embed_batch() → {len(batch)} vectors")

    sim = EmbeddingEngine.cosine_similarity(
        engine.embed("cat"),
        engine.embed("dog"),
    )
    print(f"  cosine_similarity('cat', 'dog') = {sim:.4f}")


def demo_perception_pipeline():
    """PerceptionPipeline: auto-embed and remember."""
    from aifastdb import PerceptionPipeline

    print("\n=== Perception Pipeline ===")
    pipe = PerceptionPipeline()

    result = pipe.remember_with_embedding(
        "The mitochondria is the powerhouse of the cell",
        "bio-001",
        tags=["biology"],
    )
    print(f"  ID: {result['id']}")
    print(f"  Embedding dim: {result['dimension']}")
    print(f"  Tags: {result['tags']}")
    print(f"  Has reasoning: {pipe.has_reasoning}")


def demo_pandas_integration():
    """pandas integration: to_dataframe, graph_to_dataframes."""
    try:
        import pandas as pd
    except ImportError:
        print("\n=== pandas Integration (SKIPPED — pandas not installed) ===")
        return

    from aifastdb import SocialGraphV2
    from aifastdb.pandas_ext import to_dataframe, graph_to_dataframes

    print("\n=== pandas Integration ===")
    with tempfile.TemporaryDirectory() as tmpdir:
        with SocialGraphV2(os.path.join(tmpdir, "social")) as sg:
            sg.add_person({"name": "Alice", "age": 30})
            sg.add_person({"name": "Bob", "age": 28})
            sg.add_person({"name": "Carol", "age": 32})

            df = to_dataframe(sg.list_persons())
            print(f"  Persons DataFrame: {len(df)} rows × {len(df.columns)} cols")
            if "name" in df.columns:
                print(f"  Names: {df['name'].tolist()}")

            export = sg.export_graph()
            entities_df, relations_df = graph_to_dataframes(export)
            print(f"  Entities: {len(entities_df)}, Relations: {len(relations_df)}")


if __name__ == "__main__":
    print("AiFastDb — Quick Start Demo")
    print("=" * 50)

    demo_core_database()
    demo_social_graph()
    demo_document_store()
    demo_embedding()
    demo_perception_pipeline()
    demo_pandas_integration()

    print("\n✅ All demos completed successfully!")
