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(stage_responses):
    """
    Template tag to get all responses flattened for table display.
    Usage: {% get_all_responses_flat stage_responses as all_responses %}
    """
    all_responses = []
    if stage_responses:
        for stage_id, responses in stage_responses.items():
            if responses:  # Check if responses list exists and is not empty
                for response in responses:
                    # Check if response is an object or string
                    if hasattr(response, 'stage') and hasattr(response, 'field'):
                        stage_name = response.stage.name if hasattr(response.stage, 'name') else f"Stage {stage_id}"
                        field_label = response.field.label if hasattr(response.field, 'label') else "Unknown Field"
                        field_type = response.field.get_field_type_display() if hasattr(response.field, 'get_field_type_display') else "Unknown Type"
                        required = response.field.required if hasattr(response.field, 'required') else False
                        value = response.value if hasattr(response, 'value') else response
                        uploaded_file = response.uploaded_file if hasattr(response, 'uploaded_file') else None
                    else:
                        stage_name = f"Stage {stage_id}"
                        field_label = "Unknown Field"
                        field_type = "Text"
                        required = False
                        value = response
                        uploaded_file = None

                    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
