from django.template import Template, Context
import re


def render_universal_segment(segment, context_data):
    segment_type = segment.get('segment_type', 'unknown')
    raw_content = segment.get('content')

    if raw_content is None:
        content = []
    elif isinstance(raw_content, dict):
        content = [raw_content]
    elif isinstance(raw_content, list):
        content = raw_content
    else:
        content = [raw_content]

    rendered = []
    context = Context(context_data)

    if segment_type == 'organization':
        rendered.append(
            f'<div class="front-page">'
            f'<img src="path/to/your/logo.png" alt="Risklet Logo" class="logo">'
            f'<h1>Cyber Risk Assessment Report</h1>'
            f'<p>Comprehensive Evaluation and Strategic Recommendations for Enhanced Cybersecurity Posture</p>'
            f'<div class="prepared-by">'
            f'<p>Prepared for</p>')
        for item in content:
            name = Template(item.get('name', '')).render(context)
            date = Template(item.get('date', '')).render(context)
            if name:
                rendered.append(f'<p><strong>{name}</strong></p>')
            rendered.append(f'<p>Prepared by</p>'
                            f'<p><strong>Risklet</strong></p>'
                            f'</div>')
            if date:
                rendered.append(f'<p style="margin-top: 40px;">{date}</p>')
        rendered.append(f'</div>')
        return '\n'.join(rendered)
    
    elif segment_type == 'disclaimer':
        rendered.append(
            f'<div class="disclaimer-page">'
            f'<img src="path/to/your/logo.png" alt="Risklet Logo" class="logo">'
        )
        for item in content:
            subtitle = Template(item.get('subtitle', '')).render(context)
            description = Template(item.get('description', '')).render(context)
            if subtitle:
                rendered.append(f'<h3>{subtitle}</h3>')
            if description:
                processed_desc = []
                for line in description.split('\n'):
                    line = line.strip()
                    if line:
                        processed_desc.append(f'<p>{line}</p>')
                rendered.append('\n'.join(processed_desc))
        rendered.append(f'</div>')
        return '\n'.join(rendered)

    else:
        rendered.append(f'<div class="section">')

    for item in content:
        if not isinstance(item, dict):
            continue

        title = Template(item.get('title', '')).render(context)
        subtitle = Template(item.get('subtitle', '')).render(context)
        description = Template(item.get('description', '')).render(context)

        if title:
            rendered.append(f'<h2>{title}</h2>')

        if subtitle:
            rendered.append(f'<h3>{subtitle}</h3>')

        if description:
            processed_desc = []
            in_list = False
            for line in description.split('\n'):
                line = line.strip()
                if re.match(r'^[-•*]\s', line):
                    if not in_list:
                        processed_desc.append('<ul style="list-style-type: disc; margin-left: 20px;">')
                        in_list = True
                    processed_desc.append(f'<li>{line[2:].strip()}</li>')
                else:
                    if in_list:
                        processed_desc.append('</ul>')
                        in_list = False
                    if line:
                        processed_desc.append(f'<p>{line}</p>')
            if in_list:
                processed_desc.append('</ul>')
            rendered.append('\n'.join(processed_desc))

        if 'headers' in item and 'rows' in item:
            table_html = ['<table class="report-table" style="width: 100%; border-collapse: collapse; margin: 20px 0;">']
            table_html.append('<thead><tr>')
            for header in item['headers']:
                table_html.append(f'<th style="border: 1px solid #ddd; padding: 8px; text-align: left;">{Template(header).render(context)}</th>')
            table_html.append('</tr></thead><tbody>')
            
            for row in item['rows']:
                table_html.append('<tr>')
                for cell in row:
                    cell_content = Template(cell).render(context) if isinstance(cell, str) else ', '.join([Template(str(c)).render(context) for c in cell])
                    table_html.append(f'<td style="border: 1px solid #ddd; padding: 8px;">{cell_content}</td>')
                table_html.append('</tr>')
            table_html.append('</tbody></table>')
            rendered.append('\n'.join(table_html))

        if 'html' in item:
            html_template = Template(item['html'])
            rendered_html = html_template.render(context)
            rendered.append(rendered_html)

        if 'image' in item:
            image_url = Template(item['image']).render(context)
            rendered.append(f'<img src="{image_url}" alt="{title}" style="max-width: 100%; height: auto; margin: 20px 0;">')
        
        if 'warning' in item:
            warning_text = Template(item['warning']).render(context)
            rendered.append(f'<p style="color: #e74c3c; font-weight: bold;">{warning_text}</p>')

        if 'note' in item:
            note_text = Template(item['note']).render(context)
            rendered.append(f'<p><em>{note_text}</p></em>')

    if 'html' in segment:
        html_template = Template(segment['html'])
        rendered_html = html_template.render(context)
        rendered.append(rendered_html)

    rendered.append('</div>')
    return '\n'.join(rendered)

def render_template(template_segments, context_data):
    final_output = []
    container_segments = []
    disclaimer_segment = None

    for segment in template_segments:
        segment_type = segment.get('segment_type', 'unknown')
        if segment_type == 'organization':
            final_output.append(render_universal_segment(segment, context_data))
        elif segment_type == 'disclaimer':
            disclaimer_segment = segment
        else:
            container_segments.append(segment)

    if container_segments:
        container_html = ['<div class="container">']
        for segment in container_segments:
            container_html.append(render_universal_segment(segment, context_data))
        container_html.append('</div>')
        final_output.append('\n'.join(container_html))

    if disclaimer_segment:
        final_output.append(render_universal_segment(disclaimer_segment, context_data))

    return '\n'.join(final_output)