#!/usr/bin/env python3
"""
Standalone script to import JSON analysis files into the Quber RAG database.

This script can be run independently of the Quber CLI for batch importing.

Usage:
    python scripts/import_json_to_db.py /path/to/file.json
    python scripts/import_json_to_db.py /path/to/directory/ --pattern "*_analysis.json"
"""

import sys
from pathlib import Path

# Add src to path for imports
sys.path.insert(0, str(Path(__file__).parent.parent / "src"))

import argparse

from loguru import logger

from quber.db.connection import get_engine, init_db
from quber.db.importer import get_import_stats, import_directory, import_json_file


def main():
    """Main entry point for the import script."""
    parser = argparse.ArgumentParser(
        description="Import JSON analysis files into the Quber RAG database",
        formatter_class=argparse.RawDescriptionHelpFormatter,
    )

    parser.add_argument("path", help="Path to JSON file or directory")
    parser.add_argument(
        "--pattern",
        default="*_analysis.json",
        help="File pattern for directory imports (default: *_analysis.json)",
    )
    parser.add_argument("--init-db", action="store_true", help="Initialize database schema before importing")
    parser.add_argument("--drop", action="store_true", help="Drop existing tables (WARNING: data loss)")
    parser.add_argument("--stats", action="store_true", help="Show database statistics after import")
    parser.add_argument("--verbose", "-v", action="store_true", help="Enable verbose logging")

    args = parser.parse_args()

    # Configure logging
    log_level = "DEBUG" if args.verbose else "INFO"
    logger.remove()
    logger.add(sys.stderr, level=log_level)

    # Initialize database if requested
    if args.init_db:
        logger.info("Initializing database schema...")
        try:
            engine = get_engine()
            init_db(engine, drop_all=args.drop)
            logger.success("Database initialized")
        except Exception as e:
            logger.error(f"Failed to initialize database: {e}")
            sys.exit(1)

    # Import data
    path = Path(args.path)

    if not path.exists():
        logger.error(f"Path not found: {path}")
        sys.exit(1)

    try:
        if path.is_file():
            # Import single file
            logger.info(f"Importing file: {path}")
            doc = import_json_file(path)
            logger.success(f"Imported {doc.filename}: {len(doc.tables)} tables")

        elif path.is_dir():
            # Import directory
            logger.info(f"Importing directory: {path} (pattern: {args.pattern})")
            docs = import_directory(path, pattern=args.pattern)
            total_tables = sum(len(doc.tables) for doc in docs)
            logger.success(f"Imported {len(docs)} documents with {total_tables} total tables")

        else:
            logger.error(f"Invalid path: {path}")
            sys.exit(1)

    except Exception as e:
        logger.error(f"Import failed: {e}")
        sys.exit(1)

    # Show statistics if requested
    if args.stats:
        logger.info("Fetching database statistics...")
        try:
            stats_data = get_import_stats()
            print("\n" + "=" * 50)
            print("Database Statistics")
            print("=" * 50)
            print(f"Total documents: {stats_data['total_documents']}")
            print(f"Total tables: {stats_data['total_tables']}")
            print(f"Avg tables/doc: {stats_data['avg_tables_per_doc']}")

            if stats_data["documents"]:
                print("\nDocuments:")
                for doc in stats_data["documents"]:
                    print(f"  • {doc['filename']}: {doc['tables']} tables, {doc['pages']} pages")
            print("")

        except Exception as e:
            logger.error(f"Failed to get statistics: {e}")


if __name__ == "__main__":
    main()
