from django.core.management.base import BaseCommand
import json
from django.utils import timezone

from igny8_core.business.automation.models import AutomationRun
from igny8_core.business.automation.services import AutomationService

class Command(BaseCommand):
    help = 'Dump current processing state for all running automation runs to the logs (and stdout)'

    def handle(self, *args, **options):
        runs = AutomationRun.objects.filter(status='running')
        if not runs.exists():
            self.stdout.write('No running automation runs found')
            return

        for run in runs:
            try:
                svc = AutomationService.from_run_id(run.run_id)
                state = svc.get_current_processing_state()
                snapshot = {
                    'timestamp': timezone.now().isoformat(),
                    'run_id': run.run_id,
                    'site_id': run.site.id,
                    'account_id': run.account.id,
                    'state': state,
                }
                # Append to a global processing snapshot file
                out_path = '/data/app/logs/automation/processing_snapshots.jsonl'
                try:
                    with open(out_path, 'a') as f:
                        f.write(json.dumps(snapshot) + "\n")
                except Exception as e:
                    self.stderr.write(f'Failed to write snapshot to {out_path}: {e}')

                # Also use the run-specific trace via logger
                try:
                    svc.logger.append_trace(run.account.id, run.site.id, run.run_id, {
                        'event': 'processing_snapshot',
                        'snapshot': snapshot,
                    })
                except Exception:
                    pass

                self.stdout.write(f'Wrote snapshot for run {run.run_id}')
            except Exception as e:
                self.stderr.write(f'Error processing run {run.run_id}: {e}')
