"""
Management command to test LiuYao AI analysis.

This command takes a LiuYao ID and generates an AI analysis for it.
"""
import json
from django.core.management.base import BaseCommand
from django.utils import timezone
from liuyao.models import liuyao
from ai.utils.liuyao_analysis import prepare_liuyao_prompt, analyze_liuyao
from ai.utils.i18n import normalize_language

class Command(BaseCommand):
    help = 'Test LiuYao AI analysis with specified model and provider'

    def add_arguments(self, parser):
        parser.add_argument('liuyao_id', type=int, help='ID of the LiuYao to analyze')
        parser.add_argument('--provider', type=str, help='Provider to use (groq, openai, etc.)', required=False)
        parser.add_argument('--model', type=str, help='Model to use', required=False)
        parser.add_argument('--inspect', action='store_true', help='Only inspect the prompt without calling API')
        parser.add_argument('--debug', action='store_true', help='Print debug information')
        parser.add_argument('--output', type=str, help='Save result to file', required=False)
        parser.add_argument(
            '--language',
            type=str,
            default='zh-hans',
            choices=['zh-hans', 'en'],
            help='Language of the prompt/template (default: zh-hans)'
        )

    def handle(self, *args, **options):
        liuyao_id = options['liuyao_id']
        provider = options.get('provider')
        model = options.get('model')
        inspect_only = options.get('inspect', False)
        debug = options.get('debug', False)
        output_file = options.get('output')
        language = normalize_language(options.get('language') or 'zh-hans')
        
        try:
            # Get the LiuYao instance
            liuyao_obj = liuyao.objects.get(id=liuyao_id)
            self.stdout.write(self.style.SUCCESS(f"Found LiuYao: {liuyao_obj}"))
            
            # Display basic information
            self.stdout.write(f"Question: {liuyao_obj.question}")
            self.stdout.write(f"Date: {liuyao_obj.qdate}")
            
            # Display hexagram lines
            lines = []
            for i in range(6, 0, -1):  # Display from top to bottom
                line_value = getattr(liuyao_obj, f"y{i}")
                line_symbol = "—" if line_value == "111" else "- -" if line_value == "000" else "—x" if line_value == "1" else "- x"
                lines.append(f"Line {i}: {line_symbol} ({line_value})")
            
            self.stdout.write("\nHexagram:")
            for line in lines:
                self.stdout.write(line)
                
            self.stdout.write(f"Language: {language}")

            # If inspect only, just generate and print the prompt
            if inspect_only:
                prompt = prepare_liuyao_prompt(liuyao_obj, language=language)
                self.stdout.write("\n" + "="*50)
                self.stdout.write("PROMPT INSPECTION:")
                self.stdout.write("="*50)
                self.stdout.write(prompt)
                self.stdout.write("="*50)
                self.stdout.write(f"Prompt length: {len(prompt)} characters")
                return
                
            # Otherwise, run the analysis
            self.stdout.write(self.style.SUCCESS("\nGenerating AI analysis..."))
            start_time = timezone.now()
            
            result = analyze_liuyao(liuyao_obj, model_key=model, provider=provider, language=language)
            
            end_time = timezone.now()
            duration = (end_time - start_time).total_seconds()
            
            if not result:
                self.stdout.write(self.style.ERROR(f"Analysis failed for LiuYao {liuyao_id}"))
                return
                
            # Print the result
            self.stdout.write(self.style.SUCCESS(f"\nAnalysis completed in {duration:.2f} seconds"))
            self.stdout.write(f"Provider: {result.get('provider')}")
            self.stdout.write(f"Model: {result.get('model')}")
            
            # Output different sections
            sections = result.get('sections', {})
            if sections:
                self.stdout.write("\nANALYSIS SECTIONS:")
                for section_name, content in sections.items():
                    if content and isinstance(content, str):  # Make sure content is a string
                        self.stdout.write(f"\n--- {section_name.upper().replace('_', ' ')} ---")
                        self.stdout.write(content[:200] + "..." if len(content) > 200 else content)
                    elif content:  # If content is not a string but exists
                        self.stdout.write(f"\n--- {section_name.upper().replace('_', ' ')} ---")
                        self.stdout.write(str(content)[:200] + "..." if len(str(content)) > 200 else str(content))
            
            # Print the full analysis in debug mode
            if debug:
                self.stdout.write("\n" + "="*50)
                self.stdout.write("FULL ANALYSIS:")
                self.stdout.write("="*50)
                self.stdout.write(result.get('liuyao_analysis', ''))
                self.stdout.write("="*50)
                
                if 'think' in result and result['think']:
                    self.stdout.write("\n" + "="*50)
                    self.stdout.write("THINKING PROCESS:")
                    self.stdout.write("="*50)
                    self.stdout.write(result['think'])
                    self.stdout.write("="*50)
            
            # Save to file if requested
            if output_file:
                with open(output_file, 'w') as f:
                    json.dump(result, f, ensure_ascii=False, indent=2)
                self.stdout.write(self.style.SUCCESS(f"Analysis saved to {output_file}"))
                
        except liuyao.DoesNotExist:
            self.stdout.write(self.style.ERROR(f"LiuYao with ID {liuyao_id} not found"))
        except Exception as e:
            self.stdout.write(self.style.ERROR(f"Error: {e}")) 