#!/usr/bin/env python
"""
Integration test for code query to report workflow.

This script tests the full pipeline from a code-related query to a report.
"""

import os
import sys
import asyncio
import argparse
from datetime import datetime

# Add parent directory to path to import modules
sys.path.append(os.path.dirname(os.path.dirname(os.path.dirname(os.path.abspath(__file__)))))

from query.query_processor import get_query_processor
from scripts.query_to_report import query_to_report
from report.report_templates import QueryType
from report.report_detail_levels import DetailLevel


async def test_code_query(query: str = "How to implement a binary search in Python?", detail_level: str = "brief"):
    """Test the code query to report workflow."""
    # Process the query to verify it's detected as code
    print(f"\nTesting code query detection for: {query}")
    query_processor = get_query_processor()
    structured_query = await query_processor.process_query(query)
    
    # Check if query is detected as code
    is_code = structured_query.get('is_code', False)
    print(f"Detected as code query: {is_code}")
    
    if not is_code:
        # Force code query type
        print("Manually setting to code query type for testing")
        structured_query['is_code'] = True
    
    # Generate timestamp for unique output files
    timestamp = datetime.now().strftime("%Y%m%d_%H%M%S")
    output_file = f"test_code_query_{timestamp}.md"
    
    # Generate report
    print(f"\nGenerating {detail_level} report for code query...")
    await query_to_report(
        query=query,
        output_file=output_file,
        detail_level=detail_level,
        query_type=QueryType.CODE.value,
        is_code=True
    )
    
    print(f"\nReport generated and saved to: {output_file}")
    
    # Display the start of the report
    try:
        with open(output_file, 'r', encoding='utf-8') as f:
            content = f.read()
            preview_length = min(500, len(content))
            print(f"\nReport preview:\n{'-' * 40}\n{content[:preview_length]}...\n{'-' * 40}")
            print(f"Total length: {len(content)} characters")
    except Exception as e:
        print(f"Error reading report: {e}")
    
    return output_file


def main():
    """Parse arguments and run the test."""
    parser = argparse.ArgumentParser(description='Test code query to report pipeline')
    parser.add_argument('--query', '-q', type=str, default="How to implement a binary search in Python?",
                      help='The code-related query to test')
    parser.add_argument('--detail-level', '-d', type=str, default="brief",
                      choices=['brief', 'standard', 'detailed', 'comprehensive'],
                      help='Level of detail for the report')
    
    args = parser.parse_args()
    asyncio.run(test_code_query(query=args.query, detail_level=args.detail_level))


if __name__ == "__main__":
    main()