import os
import re

ROOT = r"c:\Users\Islam\Documents\Dubai-South-lp"
IMAGES_DIR = os.path.join(ROOT, "DUBAI-SOUTH-IMAGES")

PROJECTS = [
    {
        "name": "Aristo",
        "folder": "ARISTO",
        "location": "Dubai South, Dubai",
        "short_desc": "Aristo is a boutique residential development by OKSA Developer offering modern apartments with contemporary architecture, lifestyle amenities, and smart urban living in Dubai South.",
        "beds": "Studio, 1 & 2",
        "type": "Apartments",
        "payment": "50/50",
        "price": "Ask for Availability*",
        "handover": "Q4 2028"
    },
    {
        "name": "Monaco Mansions",
        "folder": "MONACO",
        "location": "Dubai South, Dubai",
        "short_desc": "Monaco Mansions is an ultra-luxury mansion development within the Azizi Venice master community, offering large waterfront estates designed for high-end residential living.",
        "beds": "6, 7, & 8",
        "type": "Luxurious Mansions",
        "payment": "TBA",
        "price": "Ask for Availability*",
        "handover": "TBA"
    },
    {
        "name": "Azizi Venice",
        "folder": "VENICE",
        "location": "Dubai South, Dubai",
        "short_desc": "Phase-based delivery beginning around Q4 2026. Lagoon community, waterfront living, canal promenade, mixed-use lifestyle district.",
        "beds": "Studio, 1, 2, & 3",
        "type": "Apartments",
        "payment": "50/50",
        "price": "Ask for Availability*",
        "handover": "Q4 2026"
    },
    {
        "name": "The Eighty Three",
        "folder": "83",
        "location": "Dubai South, Dubai",
        "short_desc": "The Eighty Three is a boutique residential development by OKSA Developer offering modern apartments designed with contemporary architecture, lifestyle amenities, and efficient layouts in Dubai South’s growing residential district.",
        "beds": "Studio, 1, & 2",
        "type": "Apartments",
        "payment": "60/40",
        "price": "Ask for Availability*",
        "handover": "Q4 2026"
    },
    {
        "name": "Casa Aura",
        "folder": "CASA AURA",
        "location": "Dubai South, Dubai",
        "short_desc": "Casa Aura Residence is a residential apartment development by AGN Developer located in Dubai South.",
        "beds": "Studio, 1, 2, & 3",
        "type": "Apartment",
        "payment": "60/40",
        "price": "Ask for Availability*",
        "handover": "Q3 2027"
    },
    {
        "name": "South Living",
        "folder": "SOUTH LIVING",
        "location": "Dubai South, Dubai",
        "short_desc": "South Living is an apartment development in Dubai South designed to offer contemporary homes with lifestyle amenities and access to the surrounding residential district.",
        "beds": "Studio, 1, 2, & 3",
        "type": "Apartments",
        "payment": "60/40",
        "price": "Ask for Availability*",
        "handover": "Q3 2026"
    },
    {
        "name": "Hayat",
        "folder": "HAYAT",
        "location": "Dubai South, Dubai",
        "short_desc": "Hayat is a townhouse community in Dubai South designed for family living with landscaped parks, pedestrian walkways, and neighborhood amenities within the Residential District.",
        "beds": "3, 4, & 5",
        "type": "Townhouses",
        "payment": "65/35",
        "price": "Ask for Availability*",
        "handover": "Q3 2028"
    },
    {
        "name": "South Square",
        "folder": "SOUTH SQUARE",
        "location": "Dubai South, Dubai",
        "short_desc": "South Square is a residential development by Dubai South Properties offering modern apartments designed around community living and lifestyle amenities.",
        "beds": "1, 2, & 3",
        "type": "Apartments",
        "payment": "75/25",
        "price": "Ask for Availability*",
        "handover": "Q4 2028"
    },
    {
        "name": "South Bay",
        "folder": "SOUTH BAY",
        "location": "Dubai South, Dubai",
        "short_desc": "South Bay is a waterfront residential development built around a crystal lagoon and beach promenade, offering villas, townhouses, and mansions within Dubai South’s Residential District.",
        "beds": "3, 4, 5, 6, & 7",
        "type": "Townhouses, Villas, and Mansions",
        "payment": "50/50",
        "price": "Ask for Availability*",
        "handover": "Q4 2026"
    },
    {
        "name": "Beachfront Gates",
        "folder": "BEACHFRONT",
        "location": "Dubai South, Dubai",
        "short_desc": "Beachfront Gates is a residential apartment project within Dubai South offering community-oriented living with access to leisure and lifestyle facilities.",
        "beds": "1, 2, & 3",
        "type": "Apartments",
        "payment": "60/40",
        "price": "Ask for Availability*",
        "handover": "Q1 2027"
    },
    {
        "name": "Enre Residence by Imtiaz",
        "folder": "ENRE",
        "location": "Dubai South, Dubai",
        "short_desc": "A place that lets life flow in harmony with the great outdoors and contemporary architecture meets the quiet rhythm of nature, shaping an ambience that feels both effortless and intentional.",
        "beds": "Studio, 1, & 2",
        "type": "Apartments",
        "payment": "60/40",
        "price": "Ask for Availability*",
        "handover": "Q1 2028"
    },
    {
        "name": "Livia Residence",
        "folder": "LIVIA",
        "location": "Dubai South, Dubai",
        "short_desc": "Livia Residences is a boutique residential development by Barco Developers located in Dubai South’s Residential District, designed for comfortable urban living with contemporary architecture and lifestyle amenities.",
        "beds": "Studio, 1, 2, and 2+maid",
        "type": "Apartments",
        "payment": "30/70 & 50/50",
        "price": "Ask for Availability*",
        "handover": "Q4 2027"
    },
    {
        "name": "Westar Altair",
        "folder": "WESTAR",
        "location": "Dubai South, Dubai",
        "short_desc": "A contemporary residential development by Westar Properties located in the Residential District of Dubai South. Designed with spacious layouts, premium finishes, and floor-to-ceiling windows that maximize natural light and skyline views.",
        "beds": "Studio, 1, & 2",
        "type": "Apartments",
        "payment": "TBA",
        "price": "Ask for Availability*",
        "handover": "Q4 2026"
    },
    {
        "name": "Windsor House",
        "html_name": "WINDSOR 1",
        "folder": "WINDSOR 1 & 2",
        "location": "Dubai South, Dubai",
        "short_desc": "Windsor House is a design-led residential development by Ellington Properties offering contemporary apartments in Dubai South’s Residential District.",
        "beds": "Studios, 1, 2, & 3",
        "type": "Apartments",
        "payment": "70/30",
        "price": "Ask for Availability*",
        "handover": "Q3 2028"
    },
    {
        "name": "Windsor House II",
        "html_name": "WINDSOR 2",
        "folder": "WINDSOR 1 & 2",
        "location": "Dubai South, Dubai",
        "short_desc": "The project features thoughtfully designed homes with modern architecture, landscaped courtyards, and lifestyle amenities that reflect Ellington’s signature design philosophy.",
        "beds": "Studios, 1, 2, & 3",
        "type": "Apartments",
        "payment": "70/30",
        "price": "Ask for Availability*",
        "handover": "Q3 2028"
    }
]

def build_index():
    with open(os.path.join(ROOT, "index.html"), "r", encoding="utf-8") as f:
        content = f.read()

    # Generate Property Cards
    cards_html = ""
    for p in PROJECTS:
        html_file = f"{p.get('html_name', p['folder'])}.html"
        hp_img = f"./DUBAI-SOUTH-IMAGES/{p['folder']}/HP {p['folder']}.webp"

        card = f"""
                    <div class="col-md-6 property-item" data-location="{p['location']}" data-type="Apartments" data-price="">
                        <div class="hover overflow-hidden relative text-light text-center wow zoomIn" data-wow-delay=".0s">
                            <div class="wow scaleIn overflow-hidden">
                                <img src="{hp_img}" class="hover-scale-1-1 w-100" alt="{p['name']}" onerror="this.src='./DUBAI-SOUTH-IMAGES/{p['folder']}/HP {p['folder']}.jpg';">
                            </div>
                            <div class="abs w-100 px-4 hover-op-1 z-4 hover-mt-40 abs-centered">
                                <a class="btn-main btn-line fx-slide" href="{html_file}"><span>View Details</span></a>
                            </div>
                            <div class="abs bg-blur z-2 top-0 w-100 h-100 hover-op-1"></div>
                            <div class="abs z-2 bottom-0 p-10 w-100 text-center hover-op-0">
                                <div class="d-flex justify-content-between align-items-center">
                                    <h3 class="mb-0">{p['name']}</h3>
                                </div>
                                <div class="d-flex justify-content-between align-items-center">
                                    <span>{p['location']}</span>
                                    <span class="badge bg-dark"> <i class="fa-solid fa-bed me-1"></i>{p['beds']} Beds</span>
                                </div>
                                <div class="d-flex justify-content-between align-items-center mt-2">
                                    <span class="badge bg-dark">{p['type']}</span>
                                    <span class="badge bg-light text-dark">{p['price']}</span>
                                </div>
                                <small class="d-block mt-4" style="font-size: 0.85em; color: #e0cf1b;">*Prices are subject to change based on inventory availability*</small>
                            </div>
                            <div class="gradient-edge-bottom abs w-100 h-40 bottom-0"></div>
                        </div>
                    </div>
"""
        cards_html += card

    # Replace Properties Container Content
    start_tag = '<div class="row g-4" id="propertiesContainer">'
    end_tag = '</div>\n                <!-- Show More Button -->'
    
    start_idx = content.find(start_tag)
    end_idx = content.find(end_tag)

    if start_idx != -1 and end_idx != -1:
        content = content[:start_idx + len(start_tag)] + "\n" + cards_html + "\n                " + content[end_idx:]

    ######################################################
    # Text replacements in index.html for Hero and About
    ######################################################
    # Update title
    content = content.replace("<title>MIRA DEVELOPMENTS</title>", "<title>Dubai South</title>")
    content = content.replace("Mira Developments", "Dubai South")
    content = content.replace("Mira Development", "Dubai South")

    # Update Hero paragraph
    content = re.sub(
        r'<h4 class="fw-400">\s*A forward-thinking real estate developer.*?</h4>',
        '<h4 class="fw-400">A future-focused master-planned city offering integrated residential communities, business hubs, and aviation-driven growth near Expo City Dubai and Al Maktoum International Airport.</h4>',
        content,
        flags=re.DOTALL
    )

    # Update Slides to look at DUBAI-SOUTH-IMAGES/!!!SLIDES HERE
    content = content.replace("./MIRA-IMAGES/!!SLIDES HERE/", "./DUBAI-SOUTH-IMAGES/!!!SLIDES HERE/")
    content = content.replace("./MIRA-IMAGES/!!!SLIDES HERE/", "./DUBAI-SOUTH-IMAGES/!!!SLIDES HERE/")

    # Update About Section
    about_text = """<p class="wow fadeInUp" data-wow-delay=".6s">Dubai South, also known as “Dubai World Central,” is one of Dubai’s largest master-planned urban developments, spanning approximately 145 square kilometers around Al Maktoum International Airport, the future largest airport in the world. The community was designed to support Dubai’s long-term economic vision by integrating residential neighborhoods, logistics hubs, aviation districts, and commercial zones into one cohesive ecosystem.</p>
                            <p class="wow fadeInUp" data-wow-delay=".6s">Strategically located near Expo City Dubai, Dubai South connects residents and businesses to major highways, free zones, and industrial districts, creating a powerful hub for trade, logistics, and innovation.</p>
                            <p class="wow fadeInUp" data-wow-delay=".6s">Residential communities within Dubai South feature modern apartments, townhouses, and villas surrounded by parks, retail centers, schools, and wellness facilities, offering a balanced environment where residents can live, work, and connect.</p>
                            <p class="wow fadeInUp" data-wow-delay=".6s">With continuous infrastructure investment, airport expansion, and growing economic activity, Dubai South continues to attract investors, businesses, and residents seeking long-term growth opportunities in one of Dubai’s fastest-developing areas.</p>"""
    
    # We replace the exact HTML blocks
    # To be safe, just replace the exact tags
    old_about_start = '<p class="wow fadeInUp" data-wow-delay=".6s">Dubai South is a Dubai-based'
    old_about_end = 'long-term investment value.</p>'
    
    start_idx = content.find(old_about_start)
    end_idx = content.find(old_about_end)
    
    if start_idx != -1 and end_idx != -1:
        content = content[:start_idx] + about_text + content[end_idx + len(old_about_end):]
    else:
        print("Could not find about text to replace!")

    with open(os.path.join(ROOT, "index.html"), "w", encoding="utf-8") as f:
        f.write(content)


def build_subpages():
    with open(os.path.join(ROOT, "VERDE.html"), "r", encoding="utf-8") as f:
        template = f.read()

    for p in PROJECTS:
        html_file = f"{p.get('html_name', p['folder'])}.html"
        html_path = os.path.join(ROOT, html_file)
        
        content = template

        # Meta tags / Titles
        content = content.replace("<title>VERDE</title>", f"<title>{p['name']}</title>")
        
        # Hero Image and Title
        content = content.replace("./MIRA-IMAGES/VERDE/PI VERDE.webp", f"./DUBAI-SOUTH-IMAGES/{p['folder']}/PI {p['folder']}.webp\" onerror=\"this.src='./DUBAI-SOUTH-IMAGES/{p['folder']}/PI {p['folder']}.jpg'")
        content = content.replace("Mira Verde", p['name'])
        content = content.replace("Tblisi Hills, Georgia", p['location'])

        # Description
        content = content.replace("Mira Verde is a large-scale luxury master-planned community offering branded residences in Tbilisi Hills, combining modern European architecture, lifestyle amenities, and panoramic city and mountain views.", p['short_desc'])

        # Details
        content = content.replace("1, 2, 3 & 5 Bedrooms", f"{p['beds']} Bedrooms")
        content = content.replace("Q4 2028", p['handover'])
        content = content.replace("<div>60/40</div>", f"<div>{p['payment']}</div>")
        content = content.replace("<div>Apartments, Townhouses, Villas & Mansions</div>", f"<div>{p['type']}</div>")
        content = content.replace("Apartments, Townhouses, Villas & Mansions", f"{p['type']}")

        # Gallery
        # Fetch the PD images from the folder
        folder_path = os.path.join(IMAGES_DIR, p['folder'])
        slider_html = ""
        if os.path.exists(folder_path):
            files = [f for f in os.listdir(folder_path) if f.startswith("PD") and (f.endswith(".webp") or f.endswith(".jpg"))]
            for file in files:
                slider_html += f'''
                                <div class="item">
                                    <div class="relative">
                                        <div class="overflow-hidden">
                                            <img src="./DUBAI-SOUTH-IMAGES/{p['folder']}/{file}" class="w-100" alt="">
                                        </div>
                                    </div>
                                </div>
'''
        
        # Replace the entire room-carousel content
        start_tag = '<div id="room-carousel" class="owl-2-cols-center owl-carousel owl-theme">'
        end_tag = '</div>\n                        </div>\n                    </div>\n                </div>\n            </div>\n\n        </section>'
        
        start_idx = content.find(start_tag)
        end_idx = content.find(end_tag)

        if start_idx != -1 and end_idx != -1:
            content = content[:start_idx + len(start_tag)] + "\n" + slider_html + "\n                            " + content[end_idx:]

        with open(html_path, "w", encoding="utf-8") as f:
            f.write(content)

if __name__ == "__main__":
    build_index()
    build_subpages()
    print("Generation complete.")
