"""
Add these routes to app/api/v1/endpoints/reference.py
after the existing /districts endpoint
"""

ADDITION = '''
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
    }
'''

# Apply to reference.py
import re

path = 'app/api/v1/endpoints/reference.py'
content = open(path).read()

# Add imports at top if not present
if 'import json as _json' not in content:
    content = content + '\n' + ADDITION
    open(path, 'w').write(content)
    print('Added banana endpoints to reference.py')
else:
    print('Already added')