import json

from django.contrib.contenttypes.fields import GenericRelation
from django.contrib.postgres.aggregates import ArrayAgg
from django.db import models

class TtPathway(models.Model):
    pos = models.ForeignKey("api.TtPos", on_delete=models.CASCADE,null=True)
    academic_term = models.ForeignKey("api.TtAcademicTerm", on_delete=models.CASCADE,null=True)
    planned_size = models.IntegerField(null=True)
    credit = models.IntegerField(null=True)
    pathway_string = models.TextField(db_comment="form by pos_module_group_module_id, this is unique")
    pathway_string_2 = models.TextField(db_comment="form by module_id, this can be repeat")
    status = models.SmallIntegerField()
    created_by = models.BigIntegerField(null=True)
    created_at = models.DateTimeField(auto_now_add=True)
    updated_by = models.BigIntegerField(null=True)
    updated_at = models.DateTimeField(auto_now=True)

    pos_module_group_module = models.ManyToManyField("api.TtPosModuleGroupModule",through="api.TtPathwayPosModuleGroupModule")

    STATUS_TO_CODE = {
        "active": 1,
        "inactive": 2,
    }

    # just used for show rules to FE, wont save in db
    PATHWAY_GENERATE_TYPE = {
        "module_required",
        "credit_required"
    }

    class Meta:
        db_table = "tt_pathway"

    @staticmethod
    def get_pathway_details(pathway_ids):
         """
         2025-12-05, currently is used for delete confirmation show pathway details only
         """
         return (
            TtPathway.objects.filter(id__in=pathway_ids)
            .select_related("academic_term", "pos")
            .annotate(
                module_name=ArrayAgg(
                    "ttpathwayposmodulegroupmodule__pos_module_group_module__module__name",
                    distinct=True
                ),
            )
        )
