import os
import shutil
import json
from fastapi.testclient import TestClient
from main import app, get_db_connection

client = TestClient(app)
CONTENT_DIR = "content"

def generate():
    # 1. Clean and create content directory
    if os.path.exists(CONTENT_DIR):
        shutil.rmtree(CONTENT_DIR)
    os.makedirs(CONTENT_DIR)
    os.makedirs(os.path.join(CONTENT_DIR, "explore"))

    # 2. Generate Home Page
    print("Generating Home Page...")
    response = client.get("/")
    with open(os.path.join(CONTENT_DIR, "index.html"), "w") as f:
        f.write(response.text)

    # 3. Generate Version History
    print("Generating Version History...")
    response = client.get("/versions")
    with open(os.path.join(CONTENT_DIR, "versions.html"), "w") as f:
        f.write(response.text)

    # 4. Generate Sitemap
    print("Generating Sitemap...")
    response = client.get("/sitemap.xml")
    with open(os.path.join(CONTENT_DIR, "sitemap.xml"), "w") as f:
        f.write(response.text)

    # 5. Generate Individual Attraction Pages
    print("Generating Attraction Pages...")
    con = get_db_connection()
    slugs = con.execute("SELECT slug FROM attractions").fetchall()
    con.close()

    for slug_tuple in slugs:
        slug = slug_tuple[0]
        path = f"/explore/{slug}"
        print(f"  -> {path}")
        response = client.get(path)
        
        # Create directory for clean URL
        target_dir = os.path.join(CONTENT_DIR, "explore", slug)
        os.makedirs(target_dir, exist_ok=True)
        with open(os.path.join(target_dir, "index.html"), "w") as f:
            f.write(response.text)

    # 6. Mock API for 'Discover More' (Optional but recommended for static exploration)
    # We generate a static JSON file that the frontend can fetch instead of a dynamic one.
    print("Generating attractions.json for static discovery...")
    os.makedirs(os.path.join(CONTENT_DIR, "api"), exist_ok=True)
    con = get_db_connection()
    # Fetch all attractions with their full details
    # We can reuse the search API logic essentially
    query = """
        SELECT 
            a.name, 
            a.description, 
            a.image_filename, 
            c.name as country_name,
            a.category,
            c.iso_code,
            a.latitude,
            a.longitude,
            a.id,
            a.slug
        FROM attractions a
        LEFT JOIN countries c ON a.country_iso = c.iso_code
    """
    results = con.execute(query).fetchall()
    
    from main import ISO3_TO_ISO2
    
    attractions = []
    for r in results:
        attr_id = r[8]
        nearby = con.execute("SELECT name, type, link FROM nearby_places WHERE attraction_id = ?", [attr_id]).fetchall()
        restaurants = [{"name": n[0], "link": n[2]} for n in nearby if n[1] == 'restaurant']
        hotels = [{"name": n[0], "link": n[2]} for n in nearby if n[1] == 'hotel']
        
        stories = con.execute("SELECT story FROM attraction_stories WHERE attraction_id = ?", [attr_id]).fetchall()
        stories = [s[0] for s in stories]
        
        attractions.append({
            "name": r[0],
            "description": r[1],
            "image_filename": r[2],
            "country_name": r[3],
            "category": r[4],
            "iso_code": ISO3_TO_ISO2.get(r[5].upper(), r[5].lower()) if r[5] else None,
            "lat": r[6],
            "lon": r[7],
            "restaurants": restaurants,
            "hotels": hotels,
            "stories": stories,
            "slug": r[9],
            "id": r[8]
        })
    con.close()
    
    with open(os.path.join(CONTENT_DIR, "api", "attractions.json"), "w") as f:
        json.dump({"attractions": attractions}, f)

    # 7. Copy static assets
    print("Copying static assets...")
    shutil.copytree("static", os.path.join(CONTENT_DIR, "static"))

    print(f"\nStatic site generation complete! Files are in the '{CONTENT_DIR}' folder.")

if __name__ == "__main__":
    generate()
