# Generated migration for Agent Orchestration models.
# Creates: automation_pipelinerun, automation_agentrun, automation_approvalgate

from django.db import migrations, models
import django.db.models.deletion
import uuid


class Migration(migrations.Migration):

    dependencies = [
        ("automation", "0003_webhook_endpoint_delivery"),
    ]

    operations = [
        migrations.CreateModel(
            name="PipelineRun",
            fields=[
                (
                    "id",
                    models.BigAutoField(
                        auto_created=True,
                        primary_key=True,
                        serialize=False,
                        verbose_name="ID",
                    ),
                ),
                (
                    "public_id",
                    models.UUIDField(db_index=True, default=uuid.uuid4, editable=False, unique=True),
                ),
                ("created_at", models.DateTimeField(auto_now_add=True, db_index=True)),
                ("updated_at", models.DateTimeField(auto_now=True)),
                (
                    "module_name",
                    models.CharField(
                        db_index=True,
                        help_text="Module name, e.g. 'inbox_referral'.",
                        max_length=128,
                    ),
                ),
                (
                    "pipeline_ref",
                    models.CharField(
                        help_text="Relative path to pipeline JSON, e.g. '.agents/pipelines/inbox-referral.pipeline.json'.",
                        max_length=512,
                    ),
                ),
                (
                    "status",
                    models.CharField(
                        choices=[
                            ("idle", "Idle — not started"),
                            ("running", "Running"),
                            ("paused", "Paused — awaiting manual gate"),
                            ("completed", "Completed"),
                            ("failed", "Failed"),
                        ],
                        db_index=True,
                        default="idle",
                        max_length=20,
                    ),
                ),
                (
                    "current_step",
                    models.PositiveSmallIntegerField(
                        default=0,
                        help_text="0-based index of the currently executing step.",
                    ),
                ),
                (
                    "qa_iteration",
                    models.PositiveSmallIntegerField(
                        default=0,
                        help_text="Current QA rejection loop iteration (0-3).",
                    ),
                ),
                (
                    "cto_approved",
                    models.BooleanField(
                        default=False,
                        help_text="Whether CTO has approved the final review.",
                    ),
                ),
                (
                    "celery_workflow_id",
                    models.CharField(
                        blank=True,
                        default="",
                        help_text="Celery workflow ID (chain/chord) for cancellation/tracking.",
                        max_length=255,
                    ),
                ),
                ("started_at", models.DateTimeField(blank=True, null=True)),
                ("completed_at", models.DateTimeField(blank=True, null=True)),
                (
                    "error_summary",
                    models.JSONField(
                        blank=True,
                        default=dict,
                        help_text="Aggregated error info if status is 'failed'.",
                    ),
                ),
            ],
            options={
                "verbose_name": "Pipeline Run",
                "verbose_name_plural": "Pipeline Runs",
                "db_table": "automation_pipelinerun",
                "ordering": ["-created_at"],
            },
        ),
        migrations.CreateModel(
            name="AgentRun",
            fields=[
                (
                    "id",
                    models.BigAutoField(
                        auto_created=True,
                        primary_key=True,
                        serialize=False,
                        verbose_name="ID",
                    ),
                ),
                (
                    "public_id",
                    models.UUIDField(db_index=True, default=uuid.uuid4, editable=False, unique=True),
                ),
                ("created_at", models.DateTimeField(auto_now_add=True, db_index=True)),
                ("updated_at", models.DateTimeField(auto_now=True)),
                (
                    "agent_id",
                    models.CharField(
                        help_text="Two-digit agent ID, e.g. '01', '07', '19'.",
                        max_length=3,
                    ),
                ),
                (
                    "agent_name",
                    models.CharField(
                        help_text="Human-readable agent name, e.g. 'Domain Architect'.",
                        max_length=128,
                    ),
                ),
                (
                    "agent_file",
                    models.CharField(
                        help_text="Relative path to agent .md file, e.g. '.agents/agents/01-domain-architect.md'.",
                        max_length=256,
                    ),
                ),
                (
                    "step_index",
                    models.PositiveSmallIntegerField(
                        help_text="Pipeline step index this agent belongs to.",
                    ),
                ),
                (
                    "parallel_group",
                    models.CharField(
                        blank=True,
                        default="",
                        help_text="Parallel group label, e.g. 'group-a'. Empty for sequential.",
                        max_length=32,
                    ),
                ),
                (
                    "depends_on",
                    models.JSONField(
                        default=list,
                        help_text="List of agent IDs this agent waits for.",
                    ),
                ),
                (
                    "output_file",
                    models.CharField(
                        help_text="Expected output .md file path.",
                        max_length=512,
                    ),
                ),
                (
                    "status",
                    models.CharField(
                        choices=[
                            ("pending", "Pending — waiting for dependencies"),
                            ("running", "Running"),
                            ("completed", "Completed successfully"),
                            ("failed", "Failed"),
                            ("skipped", "Skipped"),
                        ],
                        db_index=True,
                        default="pending",
                        max_length=20,
                    ),
                ),
                (
                    "retry_count",
                    models.PositiveSmallIntegerField(
                        default=0,
                        help_text="Number of retry attempts (max 3).",
                    ),
                ),
                (
                    "task_id",
                    models.CharField(
                        blank=True,
                        default="",
                        help_text="Celery task ID for this agent's execution.",
                        max_length=255,
                    ),
                ),
                ("started_at", models.DateTimeField(blank=True, null=True)),
                ("completed_at", models.DateTimeField(blank=True, null=True)),
                (
                    "error_message",
                    models.TextField(
                        blank=True,
                        default="",
                        help_text="Last error message if status is 'failed'.",
                    ),
                ),
                (
                    "output_summary",
                    models.JSONField(
                        blank=True,
                        default=dict,
                        help_text="Lightweight metadata about the output (line count, validation result).",
                    ),
                ),
                (
                    "pipeline_run",
                    models.ForeignKey(
                        on_delete=django.db.models.deletion.CASCADE,
                        related_name="agent_runs",
                        to="automation.pipelinerun",
                    ),
                ),
            ],
            options={
                "verbose_name": "Agent Run",
                "verbose_name_plural": "Agent Runs",
                "db_table": "automation_agentrun",
                "ordering": ["pipeline_run", "step_index", "agent_id"],
            },
        ),
        migrations.CreateModel(
            name="ApprovalGate",
            fields=[
                (
                    "id",
                    models.BigAutoField(
                        auto_created=True,
                        primary_key=True,
                        serialize=False,
                        verbose_name="ID",
                    ),
                ),
                (
                    "public_id",
                    models.UUIDField(db_index=True, default=uuid.uuid4, editable=False, unique=True),
                ),
                ("created_at", models.DateTimeField(auto_now_add=True, db_index=True)),
                ("updated_at", models.DateTimeField(auto_now=True)),
                (
                    "after_agent_id",
                    models.CharField(
                        help_text="Agent ID after which this gate fires.",
                        max_length=3,
                    ),
                ),
                (
                    "gate_type",
                    models.CharField(
                        choices=[
                            ("auto", "Automatic validation"),
                            ("manual_review", "Manual review required"),
                            ("cto_approval", "CTO approval required"),
                        ],
                        max_length=20,
                    ),
                ),
                (
                    "status",
                    models.CharField(
                        choices=[
                            ("pending", "Pending"),
                            ("passed", "Passed"),
                            ("failed", "Failed"),
                            ("awaiting_review", "Awaiting human review"),
                        ],
                        default="pending",
                        max_length=20,
                    ),
                ),
                ("description", models.TextField(blank=True, default="")),
                (
                    "reviewed_by",
                    models.CharField(
                        blank=True,
                        default="",
                        help_text="Human reviewer identifier.",
                        max_length=255,
                    ),
                ),
                ("reviewed_at", models.DateTimeField(blank=True, null=True)),
                ("notes", models.TextField(blank=True, default="")),
                (
                    "pipeline_run",
                    models.ForeignKey(
                        on_delete=django.db.models.deletion.CASCADE,
                        related_name="gates",
                        to="automation.pipelinerun",
                    ),
                ),
            ],
            options={
                "verbose_name": "Approval Gate",
                "verbose_name_plural": "Approval Gates",
                "db_table": "automation_approvalgate",
                "ordering": ["pipeline_run", "created_at"],
            },
        ),
        migrations.AddConstraint(
            model_name="agentrun",
            constraint=models.UniqueConstraint(
                fields=["pipeline_run", "agent_id"],
                name="uq_agentrun_pipeline_agent",
            ),
        ),
    ]
