#!/usr/bin/env python3
"""
Generate a simple HTML gallery for a state's exported heatmap artifacts.

The report references PNG previews (including hotspot overlays) and links to
the GeoTIFF rasters for download.
"""

import argparse
from datetime import datetime
from html import escape
from pathlib import Path


def parse_args():
    parser = argparse.ArgumentParser(
        description="Generate an HTML report summarizing exported heatmap assets."
    )
    parser.add_argument("state", help="State name (e.g., alabama).")
    parser.add_argument(
        "--title",
        default=None,
        help="Optional title for the HTML page (defaults to '<State> Heatmap Report').",
    )
    parser.add_argument(
        "--output",
        type=Path,
        default=None,
        help="Optional output HTML path (defaults to state folder).",
    )
    return parser.parse_args()


def gather_files(state_dir, patterns):
    matches = []
    for pattern in patterns:
        matches.extend(sorted(state_dir.glob(pattern)))
    unique = []
    seen = set()
    for path in matches:
        if path not in seen and path.is_file():
            unique.append(path)
            seen.add(path)
    return unique


def build_html(title, images, rasters):
    timestamp = datetime.utcnow().isoformat()
    img_sections = []
    for image in images:
        name = image.name
        img_sections.append(
            f"""
        <figure>
            <img src="{escape(name)}" alt="{escape(name)}" loading="lazy">
            <figcaption>{escape(name)}</figcaption>
        </figure>
        """
        )

    raster_links = []
    for raster in rasters:
        name = raster.name
        raster_links.append(f'<li><a href="{escape(name)}">{escape(name)}</a></li>')

    images_html = "\n".join(img_sections) if img_sections else "<p>No images found.</p>"
    rasters_html = (
        "<ul>" + "\n".join(raster_links) + "</ul>"
        if raster_links
        else "<p>No GeoTIFF rasters found.</p>"
    )

    return f"""<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="utf-8"/>
    <title>{escape(title)}</title>
    <style>
        body {{
            font-family: Arial, sans-serif;
            margin: 2rem;
            background-color: #f7f7f7;
            color: #333;
        }}
        h1, h2 {{
            color: #111;
        }}
        figure {{
            margin: 1rem 0;
        }}
        img {{
            max-width: 100%;
            border: 1px solid #ccc;
            box-shadow: 0 1px 3px rgba(0,0,0,0.2);
        }}
        figcaption {{
            margin-top: 0.5rem;
            font-size: 0.9rem;
        }}
    </style>
</head>
<body>
    <h1>{escape(title)}</h1>
    <p>Generated: {escape(timestamp)} UTC</p>
    <section>
        <h2>Image Previews</h2>
        {images_html}
    </section>
    <section>
        <h2>GeoTIFF Downloads</h2>
        {rasters_html}
    </section>
</body>
</html>
"""


def main():
    args = parse_args()
    state = args.state.lower()
    
    # Check if state is in germany subdirectory first
    germany_dir = Path("output") / "germany" / state
    if germany_dir.exists():
        state_dir = germany_dir
    else:
        state_dir = Path("output") / state
    
    if not state_dir.exists():
        raise SystemExit(f"❌ State directory not found: {state_dir}")

    title = args.title or f"{state.capitalize()} Heatmap Report"
    output_path = args.output or (state_dir / f"{state}_report.html")

    image_patterns = [
        "*heatmap*.png",
        "*road_density_*km.png",
        "*hotspots*.png",
        "*layers*.png",
    ]
    raster_patterns = ["*road_density_*km.tif"]

    images = gather_files(state_dir, image_patterns)
    rasters = gather_files(state_dir, raster_patterns)

    if not images and not rasters:
        raise SystemExit(f"⚠️ No exported artifacts found in {state_dir}")

    html_content = build_html(title, images, rasters)
    output_path.write_text(html_content, encoding="utf-8")
    print(f"📄 Saved HTML report to: {output_path}")


if __name__ == "__main__":
    main()
