"""
Command-line interface for mineru-rag
"""

import argparse
import sys
from pathlib import Path
from .mineru_client import MinerUClient
from .rag_builder import RAGBuilder
from .llm_client import LLMClient


def main():
    """Main CLI entry point"""
    parser = argparse.ArgumentParser(
        description="MinerU RAG - Document processing and RAG knowledge base"
    )
    
    subparsers = parser.add_subparsers(dest="command", help="Command to execute")
    
    # Process command
    process_parser = subparsers.add_parser("process", help="Process documents with MinerU")
    process_parser.add_argument("input", help="Input file or directory")
    process_parser.add_argument("-o", "--output", required=True, help="Output directory")
    process_parser.add_argument("--local", action="store_true", help="Use local vLLM backend")
    process_parser.add_argument("--local-url", default="http://127.0.0.1:30000", help="Local backend URL")
    process_parser.add_argument("--api-token", help="MinerU API token (or set MINERU_API_TOKEN)")
    
    # Build RAG command
    build_parser = subparsers.add_parser("build", help="Build RAG knowledge base")
    build_parser.add_argument("files", nargs="+", help="Markdown files to process")
    build_parser.add_argument("-l", "--library", default="default", help="Library ID")
    build_parser.add_argument("-o", "--output", help="Vector store output path")
    
    # Query command
    query_parser = subparsers.add_parser("query", help="Query RAG knowledge base")
    query_parser.add_argument("question", help="Question to ask")
    query_parser.add_argument("-l", "--library", default="default", help="Library ID")
    query_parser.add_argument("-k", type=int, default=4, help="Number of documents to retrieve")
    query_parser.add_argument("--file-id", help="Limit search to specific file")
    
    args = parser.parse_args()
    
    if not args.command:
        parser.print_help()
        sys.exit(1)
    
    try:
        if args.command == "process":
            client = MinerUClient(
                api_token=args.api_token,
                use_local=args.local,
                local_url=args.local_url
            )
            input_path = Path(args.input)
            output_path = Path(args.output)
            
            if input_path.is_file():
                result = client.process_file(input_path, output_path)
            else:
                files = list(input_path.glob("*.pdf"))
                result = client.process_files_batch(files, output_path)
            
            if result.get('success'):
                print("✅ Processing completed successfully")
            else:
                print(f"❌ Processing failed: {result.get('error')}")
                sys.exit(1)
        
        elif args.command == "build":
            rag = RAGBuilder(vector_store_path=args.output)
            files = [Path(f) for f in args.files]
            rag.build_from_files(files, library_id=args.library)
            print(f"✅ RAG knowledge base built: {args.library}")
        
        elif args.command == "query":
            rag = RAGBuilder()
            rag.load_vector_store(library_id=args.library)
            
            rag_result = rag.query(
                question=args.question,
                k=args.k,
                file_id=args.file_id
            )
            
            llm = LLMClient()
            answer = llm.query_with_rag(rag_result)
            
            print(f"\n❓ Question: {answer['question']}")
            print(f"\n💡 Answer:\n{answer['answer']}")
            print(f"\n📚 Sources ({answer['num_sources']}):")
            for i, source in enumerate(answer['sources'], 1):
                print(f"  {i}. {source['filename']} (chunk {source['chunk_index']+1})")
    
    except Exception as e:
        print(f"❌ Error: {str(e)}")
        sys.exit(1)


if __name__ == "__main__":
    main()

