from jinja2 import Template


def render_xml_no(offer_data_dict, agent_data, description, num_photos, option):
    agent_data = list(agent_data or [])
    agent_id = str(agent_data[0]) if agent_data else ""

    def _get(idx, default=""):
        try:
            value = agent_data[idx]
            return "" if value is None else str(value)
        except Exception:
            return default

    # We support multiple historical Agents table layouts by detecting where email is.
    # The current gateway has an explicit nine-column agents_v2 contract.
    # Empty email must never reinterpret access_level (index 3) as a name.
    email_idx = {7: 3, 8: 5, 9: 6}.get(len(agent_data))
    for idx in (() if email_idx is not None else (3, 5, 6)):
        candidate = _get(idx).strip()
        if "@" in candidate:
            email_idx = idx
            break

    if email_idx == 3:
        agent_name = _get(1)
        agent_surname = _get(2)
        agent_email = _get(3)
        agent_phone = _get(4)
        agent_license = _get(6)
    elif email_idx == 6:
        agent_name = _get(4)
        agent_surname = _get(5)
        agent_email = _get(6)
        agent_phone = _get(7)
        agent_license = _get(8)
    else:
        # Default (legacy) layout.
        agent_name = _get(3)
        agent_surname = _get(4)
        agent_email = _get(5)
        agent_phone = _get(6)
        agent_license = _get(7)

    #-XML template
    xml_template = """<?xml version="1.0" encoding="UTF-8"?>
    <xml>
        <export>
            <version>2.0</version>
            <type>incremental</type>
            <softwareName>InvestmentManager</softwareName>
        </export>
        <agents>
            <agent>
                <idAgent>{{ agent_id }}</idAgent>
                <isProAgentDeclaration>0</isProAgentDeclaration>
                <name>{{ agent_name }}</name>
                <surname>{{ agent_surname }}</surname>
                <phone>{{ agent_phone }}</phone>
                <email>{{ agent_email }}</email>
                <licenseNr>{{ agent_license }}</licenseNr>
                <photo>
                    <fileName>agent_{{ agent_id }}.jpg</fileName>
                </photo>
            </agent>
        </agents>
        <ads>{# pricePM #}
            <ad>{% if offer_data.idCategory == '1' or offer_data.idCategory == '4' or offer_data.idCategory == '5' %}{% set denominator = offer_data.area | float %}{% elif offer_data.idCategory == '2' or offer_data.idCategory == '3' %}{% set denominator = offer_data.areaPlot | float %}{% else %}{% set denominator = 0 %}{% endif %}{% if denominator > 0 %}{% set pricePM_value = (offer_data.price | float) / denominator %}{% else %}{% set pricePM_value = 0 %}{% endif %}{% set pricePM = "{:.2f}".format(pricePM_value) %}
                <details>
                    <id>{{ offer_data.id }}</id>
                    <sign>{{ offer_data.idCategory[0] }}{{ offer_data.idAdType[0] }}/{{ offer_data.id }}</sign>
                    <action>{{ option }}</action>
                    <idRegion>{{ offer_data.idRegion }}</idRegion>
                    <districtName>{{ offer_data.districtName }}</districtName>
                    <communeName>{{ offer_data.communeName }}</communeName>
                    <cityName>{{ offer_data.cityName }}</cityName>
                    <street>{{ offer_data.streetName }}</street>
                    <idCategory>{{ offer_data.idCategory }}</idCategory>
                    <idAdType>{{ offer_data.idAdType }}</idAdType>
                    <idAgent>{{ offer_data.idAgent }}</idAgent>{% if offer_data.idCategory == '1' and offer_data.idAdType == '1' %}
                    <idMarketType>{{ offer_data.idMarketType }}</idMarketType>{% endif %}{% if offer_data.idCategory == '2' and offer_data.idAdType == '1' %}
                    <idMarketType>{{ offer_data.idMarketType }}</idMarketType>{% endif %}{% if offer_data.idCategory == '4' and offer_data.idAdType == '1' %}
                    <idMarketType>{{ offer_data.idMarketType }}</idMarketType>{% endif %}{% if offer_data.idCategory == '5' and offer_data.idAdType == '1' %}
                    <idMarketType>{{ offer_data.idMarketType }}</idMarketType>{% endif %}{% if offer_data.idCategory == '1' or offer_data.idCategory == '2' or offer_data.idCategory == '4' or offer_data.idCategory == '5'%}
                    <area>{{ offer_data.area }}</area>{% endif %}{% if offer_data.idCategory == '3' %}
                    <area>{{ offer_data.areaPlot }}</area>{% endif %}{% if offer_data.idCategory == '1' or offer_data.idCategory == '2' %}
                    <areaUse>{{ offer_data.areaUse }}</areaUse>{% endif %}
                    <price>{{ offer_data.price }}</price>
                    <pricePM>{{ pricePM }}</pricePM>{% if offer_data.idCategory == '1' or offer_data.idCategory == '2' %}
                    <rooms>{{ offer_data.rooms }}</rooms>{% endif %}{% if offer_data.idCategory == '1' or offer_data.idCategory == '4' %}
                    <floor>{{ offer_data.floor }}</floor>{% endif %}{% if offer_data.idCategory == '1' or offer_data.idCategory == '2' or offer_data.idCategory == '4' or offer_data.idCategory == '5' %}{% if offer_data.totalFloors != '0' %}
                    <totalFloors>{{ offer_data.totalFloors }}</totalFloors>{% endif %}{% endif %}{% if offer_data.idCategory == '1' or offer_data.idCategory == '4' or offer_data.idCategory == '5'%}
                    <idBuildingType>{{ offer_data.idBuildingType }}</idBuildingType>{% endif %}{% if offer_data.idCategory == '2' %}
                    <yearBuilt>{{ offer_data.yearBuilt }}</yearBuilt>{% endif %}{% if offer_data.idCategory == '1' or offer_data.idCategory == '4' %}
                    <idConditionType>{{ offer_data.idConditionType_n }}</idConditionType>{% endif %}{% if offer_data.idCategory == '2' or offer_data.idCategory == '5' %}
                    <idConditionType>{{ offer_data.idConditionType_b }}</idConditionType>{% endif %}{% if offer_data.idCategory == '1' or offer_data.idCategory == '2' %}{% if offer_data.idGarageType != '0' %}
                    <isGarageParking>1</isGarageParking>
                    <idGarageType>{{ offer_data.idGarageType }}</idGarageType>{% endif %}{% if offer_data.idGarageType == '0' %}
                    <isGarageParking>2</isGarageParking>{% endif %}{% endif %}
                    <description><![CDATA[{{ description or offer_data.Description }}]]></description>{% if offer_data.idCategory == '1' or offer_data.idCategory == '2' or offer_data.idCategory == '4' or offer_data.idCategory == '5' %}
                    <idAvailableFromYear>{{ offer_data.availableYear }}</idAvailableFromYear>
                    <idAvailableFromMonth>{{ offer_data.availableMonth }}</idAvailableFromMonth>{% endif %}{% if offer_data.idCategory == '1' %}
                    <isFurnished>{{ offer_data.isFurnished }}</isFurnished>{% endif %}{% if offer_data.idCategory == '2' or offer_data.idCategory == '3' or offer_data.idCategory == '5' %}
                    <areaPlot>{{ offer_data.areaPlot }}</areaPlot>{% endif %}{% if offer_data.idCategory == '3' %}
                    <idPlotType>{{ offer_data.idPlotType }}</idPlotType>{% endif %}{% if offer_data.idCategory == '3' %}
                    <idPlotShapeType>{{ offer_data.idPlotShapeType }}</idPlotShapeType>
                    <jPlotSituationLookType>{{ offer_data.jPlotSituationLookType }}</jPlotSituationLookType>{% endif %}{% if offer_data.idCategory == '4' or offer_data.idCategory == '5' %}
                    <idBPDestType>{{ offer_data.idBPDestType }}</idBPDestType>{% endif %}{% if offer_data.idCategory == '3' %}
                    <isMElectricity>{{ offer_data.isMElectricity }}</isMElectricity>
                    <isMGas>{{ offer_data.isMGas }}</isMGas>{% endif %}{% if offer_data.idCategory == '1' %}
                    <jHeatingType>{{ offer_data.jHeatingType }}</jHeatingType>{% endif %}{% if offer_data.idCategory == '3' %}
                    <idSewageType>{{ offer_data.idSewageType }}</idSewageType>{% endif %}{% if offer_data.idCategory == '1' %}
                    <jKitchen>{{ offer_data.jKitchen }}</jKitchen>{% endif %}{% if offer_data.idCategory == '1' or offer_data.idCategory == '2' %}{% if offer_data.idAdType == '1' %}
                    <jWindows>{{ offer_data.jWindows }}</jWindows>{% endif %}{% endif %}{% if offer_data.idCategory == '2' %}
                    <idRoofType>{{ offer_data.idRoofType }}</idRoofType>{% endif %}{% if offer_data.idCategory == '2' %}
                    <idBuildingType_d>{{ offer_data.idBuildingType_d }}</idBuildingType_d>{% endif %}{% if offer_data.idCategory == '1' and offer_data.idAdType == '1' %}
                    <rent>{{ offer_data.rent }}</rent>{% endif %}

                </details>
                <energeticCharacteristic>
                    <ecHasCertificate>2</ecHasCertificate>
                </energeticCharacteristic>
                <photos>{% for i in range(num_photos) %}
                    <photo>
                        <fileName>image_{{ offer_data.id }}_url_{{ i }}.jpg</fileName>
                    </photo>{% endfor %}
                </photos>
            </ad>
        </ads>
    </xml>
    """

    xml_template_delete = """<?xml version="1.0" encoding="UTF-8"?>
    <xml>
        <export>
            <version>2.0</version>
            <type>incremental</type>
            <softwareName>InvestmentManager</softwareName>
        </export>
        <agents>
            <agent>
                <idAgent>{{ agent_id }}</idAgent>
                <isProAgentDeclaration>0</isProAgentDeclaration>
                <name>{{ agent_name }}</name>
                <surname>{{ agent_surname }}</surname>
                <phone>{{ agent_phone }}</phone>
                <email>{{ agent_email }}</email>
                <licenseNr>{{ agent_license }}</licenseNr>
                <photo>
                    <fileName>agent_{{ agent_id }}.jpg</fileName>
                </photo>
            </agent>
        </agents>
        <ads>
            <ad>
                <details>
                    <id>{{ offer_data.id }}</id>
                    <action>delete</action>
                </details>
            </ad>
        </ads>
    </xml>
    """

    if option == 'insert' or option == 'update':

        #-Create a Jinja2 template from the XML string
        template = Template(xml_template)

        #-Render the template with the data
        filled_xml = template.render(
            agent_id=agent_id,
            agent_name=agent_name,
            agent_surname=agent_surname,
            agent_phone=agent_phone,
            agent_email=agent_email,
            agent_license=agent_license,
            offer_data=offer_data_dict,
            num_photos=num_photos,
            description=description,
            option=option,
        )
    
    elif option == 'delete':

        #-Create a Jinja2 template from the XML string
        template = Template(xml_template_delete)

        #-Render the template with the data
        filled_xml = template.render(
            agent_id=agent_id,
            agent_name=agent_name,
            agent_surname=agent_surname,
            agent_phone=agent_phone,
            agent_email=agent_email,
            agent_license=agent_license,
            offer_data=offer_data_dict,
            num_photos=num_photos,
            description=description,
        )

    return filled_xml
