from django.core.management.base import BaseCommand
from apps.users.models import User
from apps.agents.services import run_morning_efficiency_agent, send_morning_efficiency_email


class Command(BaseCommand):
    help = "Triggers the Morning Efficiency Agent to summarize daily action points & send emails to recruiters, hiring managers, and project managers."

    def add_arguments(self, parser):
        parser.add_argument(
            "--roles",
            type=str,
            help="Comma-separated roles to target (e.g. RECRUITER,ADMIN,INTERVIEWER)",
        )
        parser.add_argument(
            "--user",
            type=str,
            help="Specific user email to target",
        )
        parser.add_argument(
            "--dry-run",
            action="store_true",
            help="Generate action points and HTML preview without sending actual emails",
        )

    def handle(self, *args, **options):
        roles_str = options.get("roles")
        user_email = options.get("user")
        dry_run = options.get("dry_run", False)

        self.stdout.write(self.style.SUCCESS("Starting Morning Efficiency Agent execution..."))

        if user_email:
            try:
                user = User.objects.get(email=user_email)
                res = send_morning_efficiency_email(user, dry_run=dry_run)
                if res.get("ok"):
                    self.stdout.write(self.style.SUCCESS(f"Successfully processed {user.email}: {res['action_point_count']} action points identified."))
                else:
                    self.stdout.write(self.style.ERROR(f"Failed processing {user.email}: {res.get('error')}"))
            except User.DoesNotExist:
                self.stdout.write(self.style.ERROR(f"User with email '{user_email}' not found."))
            return

        roles = [r.strip().upper() for r in roles_str.split(",")] if roles_str else None
        results = run_morning_efficiency_agent(target_roles=roles, dry_run=dry_run)

        successful = [r for r in results if r.get("ok")]
        self.stdout.write(
            self.style.SUCCESS(
                f"Finished processing Morning Efficiency Agent. Total users: {len(results)}, Successful: {len(successful)} (Dry Run: {dry_run})"
            )
        )
