"""
GET /api/v1/crops and GET /api/v1/districts

Lets the client's frontend populate dropdowns dynamically rather than
hardcoding the supported crop/district list in their own codebase —
when the project coordinator updates data/lookup/*.json and redeploys,
the frontend picks up the change automatically on next load.

Accepts either a logged-in customer (JWT, via the SaaS dashboard) or a
service API key — same dual-auth pattern as /analyze (see
app/core/dual_auth.py). These endpoints only return public reference
data (no user-specific content), so either auth mode is sufficient.
"""

from fastapi import APIRouter, Depends

from app.core.dual_auth import AuthContext, get_auth_context
from app.services.reference_data import reference_data

router = APIRouter()


@router.get("/crops")
async def list_crops(auth: AuthContext = Depends(get_auth_context)) -> dict:
    return {"crops": reference_data.list_crops()}


@router.get("/districts")
async def list_districts(auth: AuthContext = Depends(get_auth_context)) -> dict:
    return {"districts": reference_data.list_districts()}

import json as _json
import os as _os

def _load_banana_data():
    base = _os.path.join(_os.path.dirname(__file__), '..', '..', '..', 'data', 'lookup')
    try:
        with open(_os.path.normpath(_os.path.join(base, 'state_districts.json'))) as f:
            states = _json.load(f)
        with open(_os.path.normpath(_os.path.join(base, 'banana_varieties.json'))) as f:
            varieties = _json.load(f)
        return states, varieties
    except Exception as e:
        return {}, {}

_STATE_DISTRICTS, _BANANA_VARIETIES = _load_banana_data()

@router.get("/banana/states")
async def list_states(auth: AuthContext = Depends(get_auth_context)) -> dict:
    return {"states": sorted(_STATE_DISTRICTS.keys())}

@router.get("/banana/districts/{state}")
async def list_districts_by_state(
    state: str,
    auth: AuthContext = Depends(get_auth_context)
) -> dict:
    state_lower = state.lower().strip()
    districts = _STATE_DISTRICTS.get(state_lower, [])
    return {"state": state_lower, "districts": districts}

@router.get("/banana/varieties/{state}/{district}")
async def list_banana_varieties(
    state: str,
    district: str,
    auth: AuthContext = Depends(get_auth_context)
) -> dict:
    state_lower   = state.lower().strip()
    district_lower = district.lower().strip()
    varieties = _BANANA_VARIETIES.get(state_lower, {}).get(district_lower, [])
    # Only return suitable and risky varieties (not not_suitable)
    available = [v for v in varieties if v['suitability'] in ('suitable', 'risky')]
    return {
        "state":    state_lower,
        "district": district_lower,
        "varieties": available
    }
