"""
Group Consolidation Module for Memory Deduplication

Scans the memory database for clusters of semantically similar entries,
groups them together, and uses Claude API to decide: keep_best, merge, or discard.

Features:
- Union-find clustering to find groups of related memories
- Tiered processing (auto for simple cases, LLM for complex)
- Audit trail logging to consolidation.log
- CLI and API interfaces

NOTE: This module is a backward-compatibility re-export layer.
The implementation has been split into the consolidator/ package:
- consolidator/models.py: Data classes
- consolidator/clustering.py: Union-Find and cluster detection
- consolidator/auto_rules.py: Simple auto-consolidation
- consolidator/prompting.py: LLM prompt building/parsing
- consolidator/claude_client.py: Claude Code CLI integration
- consolidator/storage.py: Apply decisions to database
- consolidator/logging.py: Audit trail
- consolidator/orchestration.py: High-level workflows
"""

import asyncio
import json
import os
from pathlib import Path

# Re-export everything from the consolidator package for backward compatibility
from consolidator import (
    # Models
    generate_cluster_id,
    Cluster,
    ConsolidationResult,
    ConsolidationReport,
    # Clustering
    UnionFind,
    find_clusters,
    tier_clusters,
    # Auto rules
    auto_consolidate_simple,
    # Prompting
    build_consolidation_prompt,
    parse_consolidation_response,
    # Claude client
    spawn_claude_code,
    consolidate_with_claude,
    # Storage
    apply_consolidation,
    # Logging
    log_consolidation,
    # Orchestration
    run_consolidation,
    scan_clusters,
    # Constants
    MAX_BATCH_SIZE
)

# Also expose the private parsing function for any legacy usage
from .consolidator.prompting import _parse_consolidation_content

__all__ = [
    # Models
    "generate_cluster_id",
    "Cluster",
    "ConsolidationResult",
    "ConsolidationReport",
    # Clustering
    "UnionFind",
    "find_clusters",
    "tier_clusters",
    # Auto rules
    "auto_consolidate_simple",
    # Prompting
    "build_consolidation_prompt",
    "parse_consolidation_response",
    "_parse_consolidation_content",
    # Claude client
    "spawn_claude_code",
    "consolidate_with_claude",
    # Storage
    "apply_consolidation",
    # Logging
    "log_consolidation",
    # Orchestration
    "run_consolidation",
    "scan_clusters",
    # Constants
    "MAX_BATCH_SIZE"
]


# CLI Interface
if __name__ == "__main__":
    import argparse
    import sys

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

    from memory_store import ContextStore
    from gpu_utils import get_device
    from sentence_transformers import SentenceTransformer

    parser = argparse.ArgumentParser(description="Memory Consolidation CLI")
    parser.add_argument("--project", "-p", required=True, help="Project name to consolidate")
    parser.add_argument("--threshold", "-t", type=float, default=0.5, help="Distance threshold (default: 0.5)")
    parser.add_argument("--max-clusters", "-m", type=int, default=10, help="Max clusters to process (default: 10)")
    parser.add_argument("--preview", action="store_true", help="Preview mode - don't apply changes")
    parser.add_argument("--scan-only", action="store_true", help="Just scan and report clusters")

    args = parser.parse_args()

    # Setup - Use PROJECTS_DIR from cli_utils
    from cli_utils import PROJECTS_DIR
    MODEL_NAME = os.environ.get("CODECONTEXT_MODEL", "all-mpnet-base-v2")

    print(f"[CLI] Loading model: {MODEL_NAME}...")
    device = get_device()
    embedder = SentenceTransformer(MODEL_NAME, device=device)

    print(f"[CLI] Opening store for project: {args.project}")
    store = ContextStore(
        db_path=str(PROJECTS_DIR / args.project / "vector_db"),
        embedder=embedder,
        device=device,
        project_name=args.project
    )

    async def main():
        if args.scan_only:
            result = await scan_clusters(store, args.project, args.threshold)
            print(json.dumps(result, indent=2))
        else:
            report = await run_consolidation(
                store,
                args.project,
                distance_threshold=args.threshold,
                max_clusters=args.max_clusters,
                preview=args.preview
            )
            print(json.dumps(report.to_dict(), indent=2))

    asyncio.run(main())
