# -------------------------
# FastAPI Application
# -------------------------
app = FastAPI(
    title="Study Area Map Generator",
    description="Professional GIS tool for generating study area maps with admin boundaries, OSM search, inset maps, and advanced cartographic features.",
    version="3.0.0",
)

class MapConfigRequest(BaseModel):
    title: str = Field(
        default="Study Area Cartographic Map",
        description="Map title to display in the header",
        example="Hawassa Region Study Area"
    )
    api_base_url: str = Field(
        default="http://196.191.180.142/gie/api",
        description="Base URL for API endpoints (admin_levels.php and admin_boundaries.php)",
        example="http://196.191.180.142/gie/api"
    )
    subcities_endpoint: str = Field(
        default="http://196.191.180.142/gie/api/subcities.php",
        description="API endpoint for subcities GeoJSON data",
        example="http://196.191.180.142/gie/api/subcities.php"
    )
    basemap: Literal["osm", "cartodb", "esri_imagery"] = Field(
        default="cartodb",
        description="Basemap style: osm (OpenStreetMap), cartodb (CartoDB Positron), esri_imagery (ESRI World Imagery)",
        json_schema_extra={"enum": ["osm", "cartodb", "esri_imagery"]}
    )
    inset_position: Literal["top", "bottom"] = Field(
        default="bottom",
        description="Position of the inset map: top (top-right) or bottom (bottom-right)",
        json_schema_extra={"enum": ["top", "bottom"]}
    )
    initial_zoom: int = Field(
        default=12,
        description="Initial zoom level for the map (1-18)",
        ge=1,
        le=18,
        example=12
    )
    center_lat: float = Field(
        default=7.0626,
        description="Initial map center latitude (WGS84 decimal degrees)",
        example=7.0626
    )
    center_lon: float = Field(
        default=38.4767,
        description="Initial map center longitude (WGS84 decimal degrees)",
        example=38.4767
    )

class MapResponse(BaseModel):
    html_page: str = Field(..., description="Complete HTML page with interactive Study Area Map Generator")
    message: str = Field(..., description="Status message")

@app.post("/", response_model=MapResponse)
async def generate_study_area_map(request: MapConfigRequest):
    """
    Generate a professional Study Area Map with advanced cartographic features.

    **Key Features:**
    - **Multi-source area selection**: Subcities, Administrative boundaries (Country/Region/Zone/District), or OSM location search
    - **Interactive controls**: Dropdown selectors, search box, basemap switcher, zoom radius adjuster
    - **Draw tools**: Point, Line, Polygon, Rectangle drawing with Replace/Overlay toggle
    - **Draggable north arrow**: Reposition by drag on the map
    - **Draggable & resizable legend**: Move and resize legend, customize colors/fonts/labels with Reset
    - **Cartographic elements**: North arrow, scale bar, coordinate grid (4-side labels with WGS84 + UTM), inset map
    - **Customization**: Custom titles, basemap selection (OSM/CartoDB/ESRI), inset position
    - **Map export**: PNG and PDF download with selectable paper size (A4/A3/Letter) and orientation
    - **Click-to-zoom**: Click any layer feature to zoom to its extent
    - **Professional GIS output**: Print-ready cartographic page layout with title, grid, frame, and all map elements

    **Study Area Selection Modes:**
    1. **Subcities**: Select Hawassa subcities from dropdown or click on map
    2. **Administrative Boundaries**: Cascading selection from Country → Region → Zone → District
    3. **OSM Search**: Search any city/location worldwide using OpenStreetMap Nominatim

    **Cartographic Features:**
    - **Coordinate Grid**: Auto-adjusting spacing with dual labels (WGS84 lat/lon + UTM Zone 37N)
    - **Grid Labels**: Positioned on all 4 sides (top, bottom, left, right) with ascending values
    - **North Arrow**: Professional SVG compass rose
    - **Scale Bar**: Metric and imperial units
    - **Inset Map**: Country outline with red box showing study area location (top-right or bottom-right)
    - **Legend**: Color-coded boundary display

    **Basemap Options:**
    - **osm**: OpenStreetMap standard view
    - **cartodb**: CartoDB Positron (clean minimal style)
    - **esri_imagery**: ESRI World Imagery (satellite view)

    **Parameters:**
    - **title**: Map title displayed in header
    - **api_base_url**: Base URL for admin_levels.php and admin_boundaries.php APIs
    - **subcities_endpoint**: URL for subcities GeoJSON API
    - **basemap**: Basemap style selection
    - **inset_position**: Position of inset map (top or bottom right)
    - **initial_zoom**: Starting zoom level (1-18)
    - **center_lat**: Initial center latitude in WGS84
    - **center_lon**: Initial center longitude in WGS84

    **Returns:**
    Complete standalone HTML page that can be deployed anywhere or opened in a browser.
    The page includes all interactive controls for runtime area selection and map customization.
    """
    logger.info(
        "Processing study area map request",
        title=request.title,
        basemap=request.basemap,
        inset_position=request.inset_position
    )

    # Generate the comprehensive HTML page
    html_content = generate_study_area_map_html(
        title=request.title,
        api_base_url=request.api_base_url,
        subcities_endpoint=request.subcities_endpoint,
        basemap=request.basemap,
        inset_position=request.inset_position,
        initial_zoom=request.initial_zoom,
        center_lat=request.center_lat,
        center_lon=request.center_lon
    )

    return MapResponse(
        html_page=html_content,
        message="Study Area Map generated successfully! The HTML includes interactive controls for area selection, basemap switching, and full cartographic features."
    )

if __name__ == "__main__":
    run_service(app)
