from django import template
from rich import print

register = template.Library()

@register.simple_tag
def get_stage_responses(stage_responses, stage_id):
    """
    Template tag to get responses for a specific stage.
    Usage: {% get_stage_responses stage_responses stage.id as stage_data %}
    """

    if stage_responses and stage_id in stage_responses:
        return stage_responses[stage_id]
    return []

@register.simple_tag
def get_all_responses_flat(submission):
    """
    Template tag to get all responses from a FormSubmission flattened for table display.
    Usage: {% get_all_responses_flat submission as flat_responses %}
    """
    all_responses = []
    if submission:
        # Fetch all responses related to this submission, selecting related field and stage objects for efficiency
        field_responses = submission.responses.all().select_related('field', 'field__stage').order_by('field__stage__order', 'field__order')

        for response in field_responses:
            stage_name = "N/A"
            field_label = "Unknown Field"
            field_type = "Text"
            required = False
            value = None
            uploaded_file = None

            if response.field:
                field_label = response.field.label
                field_type = response.field.get_field_type_display()
                required = response.field.required
                if response.field.stage:
                    stage_name = response.field.stage.name

            value = response.value
            uploaded_file = response.uploaded_file

            all_responses.append({
                'stage_name': stage_name,
                'field_label': field_label,
                'field_type': field_type,
                'required': required,
                'value': value,
                'uploaded_file': uploaded_file
            })
    return all_responses


@register.simple_tag
def get_field_response_for_submission(submission, field):
    """
    Template tag to get the FieldResponse for a specific submission and field.
    Usage: {% get_field_response_for_submission submission field as response %}
    """
    try:
        return submission.responses.filter(field=field).first()
    except:
        return None

@register.filter
def to_list(data):
    """
    Template tag to convert a string to a list.
    Usage: {% to_list "item1,item2,item3" as list %}
    """
    return data.split(",") if data else []

@register.filter
def get_schedule_candidate_ids(session, slug):
    """
    Retrieves the list of candidate IDs stored in the session for a specific job slug.
    """
    session_key = f"schedule_candidate_ids_{slug}"
    # Returns the list of IDs (or an empty list if not found)
    return session.get(session_key, [])