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",
        "beds_list": ['Studio', '1', '2'],
        "features": ['Equipped kitchens', 'Private terraces', 'Boutique residential design', 'Smart urban living'],
        "payment_steps": [('5%', 'On Booking (+4% DLD)', 'fa-book'), ('15%', 'Sales Purchase Agreement', 'fa-file-signature'), ('30%', 'During Construction', 'fa-tools'), ('50%', 'On Handover', 'fa-key')]
    },
    {
        "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",
        "beds_list": ['6', '7', '8'],
        "features": ['Waterfront estates', 'Luxury villas', 'Lagoon views', 'High-end design'],
        "payment_steps": [('TBA', 'Payment Plan Details', 'fa-file-invoice-dollar')]
    },
    {
        "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",
        "beds_list": ['Studio', '1', '2', '3'],
        "features": ['Lagoon community', 'Waterfront living', 'Canal promenade', 'Mixed-use lifestyle district'],
        "payment_steps": [('10%', 'On Booking', 'fa-book'), ('40%', 'During Construction (Installments)', 'fa-tools'), ('50%', 'On Completion', 'fa-key')]
    },
    {
        "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",
        "beds_list": ['Studio', '1', '2'],
        "features": ['Boutique low-rise architecture', 'Rooftop amenities', 'Equipped kitchens', 'Contemporary interiors'],
        "payment_steps": [('5%', 'On Booking (+4% DLD)', 'fa-book'), ('15%', 'Sales Purchase Agreement', 'fa-file-signature'), ('40%', 'During Construction', 'fa-tools'), ('40%', 'On Handover', 'fa-key')]
    },
    {
        "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",
        "beds_list": ['Studio', '1', '2', '3'],
        "features": ['Residential apartment development', 'Modern living spaces', 'Community access', 'Lifestyle amenities'],
        "payment_steps": [('20%', 'On Booking (+4% DLD)', 'fa-book'), ('40%', 'During Construction', 'fa-tools'), ('40%', 'On Completion', 'fa-key')]
    },
    {
        "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",
        "beds_list": ['Studio', '1', '2', '3'],
        "features": ['Community amenities', 'Landscaped spaces', 'Contemporary homes', 'Retail access'],
        "payment_steps": [('5%', 'On Booking', 'fa-book'), ('55%', 'During Construction', 'fa-tools'), ('16%', 'On Handover', 'fa-key'), ('24%', 'Post-Handover', 'fa-calendar-check')]
    },
    {
        "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",
        "beds_list": ['3', '4', '5'],
        "features": ['Family-oriented community', 'Landscaped parks', 'Walkable neighborhood', 'Kids play areas'],
        "payment_steps": [('10%', 'On Booking (+4% DLD)', 'fa-book'), ('55%', 'During Construction', 'fa-tools'), ('25%', 'On Handover', 'fa-key'), ('10%', 'Post-Handover', 'fa-calendar-check')]
    },
    {
        "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",
        "beds_list": ['1', '2', '3'],
        "features": ['Community-focused residential design', 'Lifestyle amenities', 'Green spaces', 'Retail centers'],
        "payment_steps": [('5%', 'Downpayment', 'fa-wallet'), ('55%', 'During Construction', 'fa-tools'), ('20%', 'On Completion', 'fa-key'), ('20%', 'Post-Handover', 'fa-calendar-check')]
    },
    {
        "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",
        "beds_list": ['3', '4', '5', '6', '7'],
        "features": ['Crystal lagoon', 'Beach club', 'Waterfront homes', 'Gated community'],
        "payment_steps": [('5%', 'On Booking', 'fa-book'), ('45%', 'During Construction', 'fa-tools'), ('20%', 'On Handover', 'fa-key'), ('30%', 'Post-Handover', 'fa-calendar-check')]
    },
    {
        "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",
        "beds_list": ['1', '2', '3'],
        "features": ['Residential community amenities', 'Leisure facilities', 'Family living spaces', 'Park access'],
        "payment_steps": [('5%', 'On Booking (+4% DLD)', 'fa-book'), ('55%', 'During Construction', 'fa-tools'), ('40%', 'On Handover', 'fa-key')]
    },
    {
        "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",
        "beds_list": ['Studio', '1', '2'],
        "features": ['World-class amenities', 'Seamless urban connectivity', 'Nature-inspired design', 'Premium finishes'],
        "payment_steps": [('20%', 'On Booking', 'fa-book'), ('40%', 'During Construction', 'fa-tools'), ('40%', 'On Completion', 'fa-key')]
    },
    {
        "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",
        "beds_list": ['Studio', '1', '2', '2+maid'],
        "features": ['Boutique low-rise building', 'Modern interiors', 'Fully fitted kitchens', 'Floor-to-ceiling windows'],
        "payment_steps": [('30%-50%', 'During Construction', 'fa-tools'), ('50%-70%', 'On Handover', 'fa-key')]
    },
    {
        "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",
        "beds_list": ['Studio', '1', '2'],
        "features": ['Contemporary architecture', 'Modern layouts', 'Spacious interiors', 'Skyline views'],
        "payment_steps": [('TBA', 'Payment Plan', 'fa-file-invoice')]
    },
    {
        "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",
        "beds_list": ['Studio', '1', '2', '3'],
        "features": ['Smart-home ready residences', 'Floor-to-ceiling windows', 'Modern interiors', 'Design-led architecture'],
        "payment_steps": [('20%', 'On Booking', 'fa-book'), ('50%', 'During Construction', 'fa-tools'), ('30%', 'On Handover', 'fa-key')]
    },
    {
        "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",
        "beds_list": ['Studio', '1', '2', '3'],
        "features": ['Smart-home ready residences', 'Landscaped courtyards', 'Modern interiors', 'Design-led architecture'],
        "payment_steps": [('20%', 'On Booking', 'fa-book'), ('50%', 'During Construction', 'fa-tools'), ('30%', 'On Handover', 'fa-key')]
    }
]

LOCATION_NEARBY_HTML = """
                    <div class="col-lg-3 col-sm-6">
                        <div class="de_count relative fs-15">
                            <h3 class="fs-30">5 Minutes</h3>
                            <div>Expo City Dubai </div>
                        </div>
                    </div>
                    <div class="col-lg-3 col-sm-6">
                        <div class="de_count relative fs-15">
                            <h3 class="fs-30">10 Minutes</h3>
                            <div>Dubai Al Maktoum Int'l Airport</div>
                        </div>
                    </div>
                    <div class="col-lg-3 col-sm-6">
                        <div class="de_count relative fs-15">
                            <h3 class="fs-30">20 Minutes</h3>
                            <div>Dubai Marina</div>
                        </div>
                    </div>
                    <div class="col-lg-3 col-sm-6">
                        <div class="de_count relative fs-15">
                            <h3 class="fs-30">25 Minutes</h3>
                            <div>Palm Jebel Ali</div>
                        </div>
                    </div>
                    <div class="col-lg-3 col-sm-6">
                        <div class="de_count relative fs-15">
                            <h3 class="fs-30">30 Minutes</h3>
                            <div>Downtown Dubai</div>
                        </div>
                    </div>
"""

def generate_beds_html(beds_list):
    html = ""
    for b in beds_list:
        title = b
        label = "Bedroom" if b in ['Studio', '1'] else "Bedrooms"
        html += f"""
                    <div class="col-lg-3 col-sm-6">
                        <div class="de_count relative fs-15">
                            <h3 class="fs-30">{title}</h3>
                            <div>
                                <h4><i class="fa-solid fa-bed"></i> {label} </h4>
                            </div>
                        </div>
                    </div>
"""
    return html

def generate_payment_html(payment_steps, handover):
    html = ""
    delay = 2
    for step in payment_steps:
        percent = step[0]
        desc = step[1]
        icon = step[2]
        html += f"""
                    <div class="col-lg-3 col-sm-6 wow fadeInUp" data-wow-delay=".{delay}s">
                        <div class="de_count relative fs-15">
                            <h3 class="fs-30 text-light"> <i class="fa-solid {icon}"></i> {percent}</h3>
                            <div class="text-light">{desc}</div>
                        </div>
                    </div>
"""
        delay += 1
        
    html += f"""
                    <div class="col-lg-3 col-sm-6 wow fadeInUp" data-wow-delay=".{delay}s">
                        <div class="de_count relative fs-15">
                            <h3 class="fs-30 text-light"><i class="fa-solid fa-calendar-alt"></i> {handover}</h3>
                            <div class="text-light">Anticipated Handover Date</div>
                        </div>
                    </div>
"""
    return html

def generate_amenities_html(features):
    left = []
    right = []
    
    # split features equally or handle odd
    half = (len(features) + 1) // 2
    left = features[:half]
    right = features[half:]
    
    left_str = "".join([f"<li>{f}</li>" for f in left])
    right_str = "".join([f"<li>{f}</li>" for f in right])
    
    return f"""
                            <div class="col-md-5 wow fadeInUp" data-wow-delay=".2s">
                                <ul class="ul-check fs-500 text-dark">
                                    {left_str}
                                </ul>
                            </div>
                            <div class="col-md-5 wow fadeInUp" data-wow-delay=".4s">
                                <ul class="ul-check fs-500 text-dark">
                                    {right_str}
                                </ul>
                            </div>
"""

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)
        
        # Read the previously generated simple HTML to NOT overwrite the gallery extraction logic?
        # Actually it's easier to just recreate it from the VERDE template completely, but using the robust new logic
        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
        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>
'''
        
        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:]

        ###########################################
        # NEW SECTION INJECTIONS
        ###########################################
        
        # Amenities
        amenities_start_tag = '<div class="row">'
        amenities_end_tag = '</div>\n                    </div>\n\n\n                </div>'
        # To make sure we replace the right one, let's use explicit regex or split around "Amenities Designed for Your Lifestyle"
        
        amenities_html = generate_amenities_html(p['features'])
        
        # Amenities block occurs after "Amenities Designed for Your Lifestyle"
        a_sig = '<div class="spacer-single spacer-double"></div>'
        a_sig_idx = content.find(a_sig)
        if a_sig_idx != -1:
            row_idx = content.find('<div class="row">', a_sig_idx)
            row_end = content.find('</div>\n                    </div>\n\n\n                </div>', row_idx)
            if row_idx != -1 and row_end != -1:
                content = content[:row_idx + len('<div class="row">')] + "\n" + amenities_html + "\n            " + content[row_end:]

        # Bedroom Types Available
        b_sig = '<h2 class="fs-40 ">Bedroom Types Available</h2>'
        b_sig_idx = content.find(b_sig)
        if b_sig_idx != -1:
            # Container ends with '</div>\n            </div>\n        </section>'
            col12_end = content.find('</div>', b_sig_idx)
            sec_end = content.find('</div>\n            </div>\n        </section>', b_sig_idx)
            if col12_end != -1 and sec_end != -1:
                content = content[:col12_end + 6] + "\n" + generate_beds_html(p['beds_list']) + "\n                " + content[sec_end:]

        # Project Location
        l_sig = '<h2 class="fs-40 ">Project Location & Nearby</h2>'
        l_sig_idx = content.find(l_sig)
        if l_sig_idx != -1:
            col12_end = content.find('</div>', l_sig_idx)
            sec_end = content.find('</div>\n            </div>\n        </section>', l_sig_idx)
            if col12_end != -1 and sec_end != -1:
                content = content[:col12_end + 6] + "\n" + LOCATION_NEARBY_HTML + "\n                " + content[sec_end:]

        # Payment Plan
        p_sig = '<h2 class="fs-40 text-light">Payment Plan</h2>'
        p_sig_idx = content.find(p_sig)
        if p_sig_idx != -1:
            col12_end = content.find('</div>', p_sig_idx)
            sec_end = content.find('<small class="d-block mt-4" style="font-size: 0.85em; color: #e0cf1b;">', p_sig_idx)
            if col12_end != -1 and sec_end != -1:
                content = content[:col12_end + 6] + "\n" + generate_payment_html(p['payment_steps'], p['handover']) + "\n                    " + content[sec_end:]


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

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