"""Bulk Story Pipeline — Export prompts to AI, Import stories back."""
import re
from pathlib import Path
from django.core.management.base import BaseCommand
from exams.models import KnowledgeComponent, StoryVersion
from exams.services.story_panel import evaluate_story
from exams.services.story_panel.prompt_builder import build_prompt

EXPORT_FILE = Path('/home/orkoworo/idealogy/api/tmp/story_prompts_export.txt')
IMPORT_FILE = Path('/home/orkoworo/idealogy/api/tmp/story_stories_import.txt')

class Command(BaseCommand):
    help = 'Export KC prompts for external AI, or import AI-generated stories.'

    def add_arguments(self, parser):
        parser.add_argument('--action', type=str, required=True, choices=['export', 'import'])
        parser.add_argument('--subject', type=str, default='Chemistry')

    def handle(self, *args, **options):
        action = options['action']
        subject = options['subject']

        if action == 'export':
            self.export_prompts(subject)
        elif action == 'import':
            self.import_stories()

    def export_prompts(self, subject):
        qs = KnowledgeComponent.objects.filter(story_status='EMPTY', subject__iexact=subject).order_by('code')
        
        EXPORT_FILE.parent.mkdir(parents=True, exist_ok=True)
        
        count = 0
        with open(EXPORT_FILE, 'w', encoding='utf-8') as f:
            for kc in qs:
                # Only export if eligible
                if not kc.misconceptions or not kc.key_terms:
                    continue
                    
                prompt = build_prompt(kc)
                f.write(f"=== START PROMPT: {kc.code} ===\n")
                f.write(prompt)
                f.write(f"\n=== END PROMPT: {kc.code} ===\n\n")
                count += 1

        self.stdout.write(self.style.SUCCESS(f"Exported {count} prompts to {EXPORT_FILE}"))
        self.stdout.write("Next step: Copy the contents of this file into Gemini/ChatGPT.")
        self.stdout.write(f"Path: {EXPORT_FILE}")

    def import_stories(self):
        if not IMPORT_FILE.exists():
            self.stdout.write(self.style.ERROR(f"Import file not found: {IMPORT_FILE}"))
            return

        text = IMPORT_FILE.read_text(encoding='utf-8')
        
        # Regex to match blocks like:
        # === START STORY: C9-CH00-GLOSSARY ===
        # Story text...
        # === END STORY: C9-CH00-GLOSSARY ===
        pattern = r'=== START STORY: ([\w-]+) ===\n(.*?)\n=== END STORY: \1 ==='
        matches = re.findall(pattern, text, re.DOTALL)

        if not matches:
            self.stdout.write(self.style.ERROR("No valid story blocks found. Check format."))
            return

        passed_count = 0
        flagged_count = 0

        for kc_code, story_text in matches:
            kc = KnowledgeComponent.objects.filter(code=kc_code).first()
            if not kc:
                self.stdout.write(self.style.WARNING(f"KC not found: {kc_code}"))
                continue

            story_text = story_text.strip()
            if not story_text:
                continue

            # Run local 6-expert panel
            verdict = evaluate_story(kc, story_text)
            status = 'PANEL_PASSED' if verdict['passed'] else 'PANEL_FLAGGED'

            # Save to KC
            kc.story = [story_text]
            kc.story_status = status
            kc.story_panel_verdict = verdict
            kc.save()

            # Save version history
            last_version = StoryVersion.objects.filter(kc=kc).order_by('-version_number').first()
            v_num = (last_version.version_number + 1) if last_version else 1
            StoryVersion.objects.create(
                kc=kc, version_number=v_num, source='PANEL_AI',
                story_text=story_text, panel_verdict=verdict
            )

            if verdict['passed']:
                passed_count += 1
                self.stdout.write(self.style.SUCCESS(f"PASSED: {kc_code} (avg {verdict['average']})"))
            else:
                flagged_count += 1
                self.stdout.write(self.style.WARNING(f"FLAGGED: {kc_code} (avg {verdict['average']})"))

        self.stdout.write(self.style.SUCCESS(f"Import complete. Passed: {passed_count}, Flagged: {flagged_count}"))
