def build_scope_tree(nodes, prefix=""):

    html = ""

    for index, node in enumerate(nodes, start=1):

        number = f"{prefix}{index}" if prefix == "" else f"{prefix}.{index}"

        node_type = node.get("node_type", "").upper()

        if node_type == "SECTION":

            html += f"""
            <div class="scope-section">

                <div class="scope-section-title">
                    {number}. {node["name"]}
                </div>
            """

        elif node_type == "SUBSECTION":

            html += f"""
            <div class="scope-subsection">

                <div class="scope-subsection-title">
                    {number}. {node["name"]}
                </div>
            """

        else:

            html += f"""
            <div class="scope-feature">

                <div class="scope-feature-title">
                    {number}. {node["name"]}
                </div>
            """

        if node.get("description"):

            html += f"""
            <div class="scope-description">
                {node["description"]}
            </div>
            """

        if node.get("children"):

            html += build_scope_tree(
                node["children"],
                number
            )

        html += "</div>"

    return html

def build_responsibility_tree(nodes, prefix=""):

    html = ""

    for index, node in enumerate(nodes, start=1):

        number = f"{prefix}{index}" if prefix == "" else f"{prefix}.{index}"

        node_type = node.get("node_type", "").upper()

        if node_type == "SECTION":

            html += f"""
            <div class="resp-section">

                <div class="resp-section-title">
                    {number}. {node["name"]}
                </div>
            """

        elif node_type == "SUBSECTION":

            html += f"""
            <div class="resp-subsection">

                <div class="resp-subsection-title">
                    {number}. {node["name"]}
                </div>
            """

        else:

            html += f"""
            <div class="resp-item">

                <div class="resp-item-title">
                    {number}. {node["name"]}
                </div>
            """

        if node.get("description"):

            html += f"""
            <div class="resp-description">
                {node["description"]}
            </div>
            """

        if node.get("children"):

            html += build_responsibility_tree(
                node["children"],
                number
            )

        html += "</div>"

    return html

def build_timeline_table(phases):
    """
    Renders the .timeline-wrapper markup consumed by the
    agreement template's PROJECT TIMELINE section.

    Data is fully dynamic — phase.phase_name, phase.start_day,
    phase.end_day and phase.progress all come from the backend
    (e.g. a queryset of TimelinePhase rows). Nothing here is
    hardcoded; only the CSS in the template changed to restyle
    this same markup as blue circles / white cards with a
    calendar-badge day pill, matching the reference UI.
    """
    if not phases:
        return ""

    html = '<div class="timeline-wrapper">'

    for index, phase in enumerate(phases, start=1):
        progress = phase.progress or 0

        html += f"""
        <div class="timeline-item">

            <div class="timeline-number">
                {index}
            </div>

            <div class="timeline-card">

                <div class="timeline-header">

                    <div>

                        <div class="timeline-title">
                        {phase.phase_name} <span class="timeline-days">Days {phase.start_day}&ndash;{phase.end_day})</span>
                        </div>

                    </div>

                    <div class="timeline-percent">
                        {progress}%
                    </div>

                </div>

                <div class="timeline-progress">

                    <div class="timeline-progress-fill"
                         style="width:{progress}%;">
                    </div>

                </div>

            </div>

        </div>
        """

    html += "</div>"

    return html

def build_payment_html(payment):
    if not payment:
        return ""

    html = f"""
    <p>
        The Parties hereby acknowledge and agree that the total consideration for the Services has been calculated based on a
        <strong>Subtotal</strong> of <strong>₹{payment.subtotal}</strong>.
        A <strong>GST of {payment.gst_percent}%</strong> has been applied in accordance with the applicable tax laws.
        A <strong>Discount of {payment.discount_percent}%</strong> has been extended to the Client as mutually agreed between the Parties.
        Further, a <strong>TDS of {payment.tds_percent}%</strong> shall be deducted wherever applicable under the prevailing provisions of law.
        Accordingly, after applying all applicable taxes, deductions, and discounts, the
        <strong>Final Payable Amount (Grand Total)</strong> under this Agreement shall be
        <strong>₹{payment.grand_total}</strong>.
    </p>
    """

    if payment.milestones.exists():
        html += """
        <h3 style="font-family: Arial, sans-serif; color: #1a1a1a; margin: 24px 0 12px;">Milestones</h3>
        <table style="width:100%; border-collapse: collapse; font-family: Arial, sans-serif; font-size: 14px; box-shadow: 0 1px 3px rgba(0,0,0,0.1);">
        <thead>
        <tr style="background-color: #b91c1c; color: #ffffff; text-align: left;">
        <th style="padding: 10px 14px; border: 1px solid #b91c1c;">Period Name</th>
        <th style="padding: 10px 14px; border: 1px solid #b91c1c; text-align: right;">Percentage</th>
        <th style="padding: 10px 14px; border: 1px solid #b91c1c; text-align: right;">Amount</th>
        <th style="padding: 10px 14px; border: 1px solid #b91c1c;">Due Date</th>
        </tr>
        </thead>
        <tbody>
        """

        for i, m in enumerate(payment.milestones.all()):
            row_bg = "#fef2f2" if i % 2 == 0 else "#ffffff"
            html += f"""
            <tr style="background-color: {row_bg};">
            <td style="padding: 8px 14px; border: 1px solid #fca5a5;">{m.milestone_name}</td>
            <td style="padding: 8px 14px; border: 1px solid #fca5a5; text-align: right;">{m.percentage}%</td>
            <td style="padding: 8px 14px; border: 1px solid #fca5a5; text-align: right;">{m.amount}</td>
            <td style="padding: 8px 14px; border: 1px solid #fca5a5;">{m.due_date}</td>
            </tr>
            """

        html += "</tbody></table>"

    return html

def build_terms_html(terms):

    if not terms:
        return ""

    html = "<ol>"

    for term in terms:

        # Always use the complete term content
        content = term.content or term.name or ""

        html += f"""
        <li>
            {content}
        </li>
        """

    html += "</ol>"

    return html

def build_signature_html(signature_data):
    """Returns HTML for the signature block, including base64 images."""
    if not signature_data:
        return ""

    agency_name = signature_data.get('agency_name', '')
    agency_designation = signature_data.get('agency_designation', '')
    client_name = signature_data.get('client_name', '')
    agency_sig = signature_data.get('agency_signature_b64')
    print(agency_sig)
    client_sig = signature_data.get('client_signature_b64')
    print(client_sig)
    html = f"""
    <div class="section section-signature">
        <p class="signature-intro">In witness whereof, the parties have executed this Agreement as of the date first written above.</p>
        <table class="signature">
            <tr>
                <td>
                    <span class="sig-role">For the Agency</span>
                    <br><br>
                    <strong>{agency_name}</strong>
                    <br>
                    {agency_designation}
                    <br><br>
                    {f'<img src="{agency_sig}" alt="Agency Signature" style="max-width:200px; max-height:80px; display:block; margin:10px 0;">' if agency_sig else '<div class="signature-line" style="width:80%;"></div>'}
                    <div class="sig-caption">Authorized Signature</div>
                </td>
                <td>
                    <span class="sig-role">For the Client</span>
                    <br><br>
                    <strong>{client_name}</strong>
                    <br>
                    Client Representative
                    <br><br>
                    {f'<img src="{client_sig}" alt="Client Signature" style="max-width:200px; max-height:80px; display:block; margin:10px 0;">' if client_sig else '<div class="signature-line" style="width:80%;"></div>'}
                    <div class="sig-caption">Authorized Signature</div>
                </td>
            </tr>
        </table>
    </div>
    """
    return html