#!/usr/bin/env python3
"""
Standalone CLI script for RAG operations
Used by Laravel via exec() for production-ready integration
"""

import sys
import json
import os
import tempfile
from pathlib import Path

# Add the current directory to the path
sys.path.append(str(Path(__file__).parent))

def main():
    """Main CLI entry point"""
    try:
        # Read input from command line arguments or stdin
        if len(sys.argv) > 1:
            input_data = json.loads(sys.argv[1])
        else:
            input_data = json.loads(sys.stdin.read())
        
        operation = input_data.get('operation', 'ingest')
        
        if operation == 'ingest':
            result = handle_ingest(input_data)
        elif operation == 'query':
            result = handle_query(input_data)
        elif operation == 'clear':
            result = handle_clear(input_data)
        elif operation == 'upload_pdf':
            result = handle_pdf_upload(input_data)
        else:
            result = {"success": False, "error": f"Unknown operation: {operation}"}
        
        print(json.dumps(result))
        
    except Exception as e:
        error_result = {"success": False, "error": str(e)}
        print(json.dumps(error_result))
        sys.exit(1)

def handle_ingest(data):
    """Handle content ingestion"""
    try:
        from app import store_document
        
        content = data.get('content', '')
        session_id = data.get('session_id', 'cli_session')
        clear_existing = data.get('clear_existing', True)
        source = data.get('source', 'cli_ingest')
        
        if not content:
            return {"success": False, "error": "Content is required"}
        
        result = store_document(content, session_id, clear_existing, source)
        
        return {
            "success": True,
            "message": f"Content indexed successfully. Chunks: {result['chunks_count']}",
            "chunks_count": result['chunks_count'],
            "session_id": session_id
        }
        
    except Exception as e:
        return {"success": False, "error": str(e)}

def handle_query(data):
    """Handle query operation"""
    try:
        from app import search_similar_chunks, generate_answer
        
        query = data.get('query', '')
        if not query:
            return {"success": False, "error": "Query is required"}
        
        # Search for similar chunks
        similar_chunks = search_similar_chunks(query, top_k=5, min_similarity=0.3)
        
        # Generate answer
        answer = generate_answer(query, similar_chunks)
        
        # Format sources
        sources = []
        if similar_chunks:
            for chunk in similar_chunks[:3]:
                sources.append({
                    'content': chunk['content'],
                    'metadata': chunk['metadata']
                })
        
        return {
            "success": True,
            "answer": answer,
            "sources": sources
        }
        
    except Exception as e:
        return {"success": False, "error": str(e)}

def handle_clear(data):
    """Handle clear operation"""
    try:
        from app import get_db_connection
        
        connection = get_db_connection()
        if not connection:
            return {"success": False, "error": "Failed to connect to database"}
        
        cursor = connection.cursor()
        cursor.execute("DELETE FROM rag_chunks")
        cursor.execute("DELETE FROM rag_documents")
        connection.commit()
        cursor.close()
        connection.close()
        
        return {
            "success": True,
            "message": "Knowledge base cleared successfully"
        }
        
    except Exception as e:
        return {"success": False, "error": str(e)}

def handle_pdf_upload(data):
    """Handle PDF upload operation"""
    try:
        from app import store_document
        from langchain_community.document_loaders import PyPDFLoader
        
        file_path = data.get('file_path', '')
        filename = data.get('filename', 'uploaded.pdf')
        clear_existing = data.get('clear_existing', True)
        
        if not file_path or not os.path.exists(file_path):
            return {"success": False, "error": "Valid file path is required"}
        
        # Load and process PDF
        loader = PyPDFLoader(file_path)
        documents = loader.load()
        
        full_content = ""
        for doc in documents:
            page_content = doc.page_content.strip()
            if page_content:
                full_content += page_content + "\n\n"
        
        if not full_content.strip():
            return {"success": False, "error": "No readable content found in PDF"}
        
        # Store the PDF content
        session_id = data.get('session_id', 'cli_pdf_session')
        result = store_document(full_content, session_id, clear_existing, f'pdf_upload:{filename}')
        
        return {
            "success": True,
            "message": f"PDF '{filename}' processed successfully",
            "chunks_created": result['chunks_count'],
            "pages_processed": len(documents),
            "session_id": session_id
        }
        
    except Exception as e:
        return {"success": False, "error": str(e)}

if __name__ == '__main__':
    main()
