#!/usr/bin/env python3
"""
Basic usage examples for Hypersets.

This script demonstrates the main features and capabilities of the hypersets package
for efficient dataset querying without full downloads.
"""

import hypersets as hs
import pandas as pd


def main():
    print("🚀 Hypersets Basic Usage Examples\n")

    # Example 1: Get dataset information instantly
    print("=" * 60)
    print("📊 Example 1: Getting Dataset Information")
    print("=" * 60)

    try:
        # Get comprehensive dataset metadata without downloading
        info = hs.get_dataset_info("omarkamali/wikipedia-monthly")

        print(f"Dataset: {info.name}")
        print(f"Total configs: {len(info.config_names)}")
        print(f"Sample configs: {info.config_names[:5]}")
        print(f"Total parquet files: {info.total_parquet_files}")
        print(f"Estimated size: {info.estimated_total_size_gb:.1f} GB")

        # Show specific config info
        if "latest.en" in info.configs:
            en_config = info.configs["latest.en"]
            print(f"\nEnglish Wikipedia config:")
            print(f"  • Splits: {list(en_config.splits.keys())}")
            if "train" in en_config.splits:
                train_split = en_config.splits["train"]
                print(f"  • Train files: {train_split.file_count}")

    except Exception as e:
        print(f"Error: {e}")

    print("\n")

    # Example 2: Basic data querying
    print("=" * 60)
    print("🎯 Example 2: Querying Data")
    print("=" * 60)

    try:
        # Basic SQL query
        result = hs.query(
            "SELECT title, LENGTH(text) as text_length FROM dataset LIMIT 10",
            dataset="omarkamali/wikipedia-monthly",
            config="latest.en",
        )

        print(f"Query returned {len(result)} rows")
        print(f"Columns: {result.columns}")

        # Convert to pandas for easy viewing
        df = result.to_pandas()
        print("\nSample results:")
        for i, row in df.head(3).iterrows():
            print(f"  {i+1}. {row['title'][:50]}... ({row['text_length']} chars)")

    except Exception as e:
        print(f"Error: {e}")

    print("\n")

    # Example 3: Sampling data
    print("=" * 60)
    print("🎲 Example 3: Random Sampling")
    print("=" * 60)

    try:
        # Sample random rows
        sample = hs.sample(
            n=5,
            dataset="omarkamali/wikipedia-monthly",
            config="latest.en",
            columns=["title", "url"],
        )

        print(f"Sampled {len(sample)} rows")

        # Show sample data
        df = sample.to_pandas()
        print("\nRandom sample:")
        for i, row in df.iterrows():
            print(f"  {i+1}. {row['title'][:60]}...")

    except Exception as e:
        print(f"Error: {e}")

    print("\n")

    # Example 4: Aggregation queries
    print("=" * 60)
    print("📈 Example 4: Aggregation")
    print("=" * 60)

    try:
        # Count total rows
        count_result = hs.count(
            dataset="omarkamali/wikipedia-monthly", config="latest.en"
        )

        print(f"Total articles: {count_result:,}")

        # More complex aggregation
        agg_result = hs.query(
            """
            SELECT 
                COUNT(*) as article_count,
                AVG(LENGTH(text)) as avg_text_length,
                MAX(LENGTH(text)) as max_text_length
            FROM dataset
            """,
            dataset="omarkamali/wikipedia-monthly",
            config="latest.en",
        )

        stats = agg_result.to_pandas().iloc[0]
        print(f"\nDataset statistics:")
        print(f"  • Articles: {stats['article_count']:,}")
        print(f"  • Average text length: {stats['avg_text_length']:.0f} chars")
        print(f"  • Maximum text length: {stats['max_text_length']:,} chars")

    except Exception as e:
        print(f"Error: {e}")

    print("\n")

    # Example 5: Schema inspection
    print("=" * 60)
    print("🔍 Example 5: Schema Inspection")
    print("=" * 60)

    try:
        # Get schema information
        schema = hs.schema(dataset="omarkamali/wikipedia-monthly", config="latest.en")

        print("Dataset schema:")
        for col in schema.columns:
            print(f"  • {col['name']}: {col['type']}")

    except Exception as e:
        print(f"Error: {e}")

    print("\n")

    # Example 6: Output formats
    print("=" * 60)
    print("📋 Example 6: Different Output Formats")
    print("=" * 60)

    try:
        # Get some data
        result = hs.head(
            n=3,
            dataset="omarkamali/wikipedia-monthly",
            config="latest.en",
            columns=["title", "url"],
        )

        # Pandas DataFrame
        df = result.to_pandas()
        print("As Pandas DataFrame:")
        print(f"  Shape: {df.shape}")
        print(f"  Columns: {list(df.columns)}")

        # HuggingFace Dataset
        try:
            hf_dataset = result.to_hf_dataset()
            print(f"\nAs HuggingFace Dataset:")
            print(f"  Length: {len(hf_dataset)}")
            print(f"  Features: {list(hf_dataset.features.keys())}")
        except Exception as e:
            print(f"\nHuggingFace conversion failed: {e}")

    except Exception as e:
        print(f"Error: {e}")

    print("\n")

    # Example 7: Caching benefits
    print("=" * 60)
    print("⚡ Example 7: Caching Performance")
    print("=" * 60)

    try:
        import time

        # Clear cache
        hs.clear_cache()

        # First call (cold)
        start = time.time()
        info1 = hs.get_dataset_info("omarkamali/wikipedia-monthly")
        first_time = time.time() - start

        # Second call (cached)
        start = time.time()
        info2 = hs.get_dataset_info("omarkamali/wikipedia-monthly")
        second_time = time.time() - start

        speedup = first_time / second_time if second_time > 0 else float("inf")

        print(f"First call (cold): {first_time:.2f}s")
        print(f"Second call (cached): {second_time:.3f}s")
        print(f"Speedup: {speedup:.0f}x")

    except Exception as e:
        print(f"Error: {e}")

    print("\n🎉 Basic usage examples completed!")


if __name__ == "__main__":
    main()
