import sys
from django.core.management.base import BaseCommand, CommandError
from django.utils import timezone
from bazi.models import Person
from ai.utils.bazi import prepare_bazi_prompt
from ai.models import PromptTemplate
import json

class Command(BaseCommand):
    help = 'Inspect the prompt that would be used for BaZi analysis'

    def add_arguments(self, parser):
        parser.add_argument('person_id', nargs='?', type=int,
                            help='ID of the person to inspect')
        parser.add_argument('--first', action='store_true',
                            help='Use first person in database (ignores person_id)')
        parser.add_argument('--list-templates', action='store_true',
                            help='List available templates in database')
        parser.add_argument('--output', type=str, default=None,
                            help='Save prompt to file instead of printing to stdout')
        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):
        # If --list-templates is specified, show available templates
        if options['list_templates']:
            self.list_templates()
            return
    
        try:
            # Get person
            if options['first']:
                person = Person.objects.first()
                if not person:
                    raise CommandError("No persons found in database")
                self.stdout.write(f"Using first person from database: ID {person.id}, Name: {person.name}")
            elif options['person_id']:
                try:
                    person = Person.objects.get(id=options['person_id'])
                except Person.DoesNotExist:
                    raise CommandError(f"Person with ID {options['person_id']} does not exist")
            else:
                raise CommandError("Either --first or person_id argument is required")

            language = options.get('language') or 'zh-hans'

            # Check for active template in database
            active_template = PromptTemplate.objects.filter(
                divination_type='bazi',
                language=language,
                status='active'
            ).order_by('-updated_at').first()
            
            if active_template:
                self.stdout.write(self.style.SUCCESS(f"Active database template found: {active_template.name}"))
                self.stdout.write(f"Last updated: {active_template.updated_at}")
                self.stdout.write(f"Created by: {active_template.created_by}")
            else:
                self.stdout.write(self.style.WARNING("No active database template found. Will use file-based template."))

            # Generate prompt
            self.stdout.write("Generating prompt...")
            prompt = prepare_bazi_prompt(person, language=language)
            
            # Output
            if options['output']:
                with open(options['output'], 'w', encoding='utf-8') as f:
                    f.write(prompt)
                self.stdout.write(self.style.SUCCESS(f"Prompt saved to {options['output']}"))
            else:
                self.stdout.write("\n--- BEGIN PROMPT ---\n")
                self.stdout.write(prompt)
                self.stdout.write("\n--- END PROMPT ---\n")
                
        except Exception as e:
            raise CommandError(f"Error: {e}")
    
    def list_templates(self):
        templates = PromptTemplate.objects.filter(divination_type='bazi').order_by('-status', '-updated_at')
        
        if not templates:
            self.stdout.write(self.style.WARNING("No BaZi templates found in database."))
            return
            
        self.stdout.write(self.style.SUCCESS(f"Found {templates.count()} BaZi templates:"))
        self.stdout.write("\n{:<40} {:<10} {:<10} {:<20} {:<20}".format(
            "Name", "Language", "Status", "Updated", "Created By"
        ))
        self.stdout.write("-" * 110)
        
        for template in templates:
            self.stdout.write("{:<40} {:<10} {:<10} {:<20} {:<20}".format(
                template.name[:40],
                template.language,
                template.status,
                timezone.localtime(template.updated_at).strftime('%Y-%m-%d %H:%M'),
                str(template.created_by) if template.created_by else "Unknown"
            )) 