"""
app/services/market_price_service.py

Direct market price lookup from Agmarknet data.
Returns current price per kg and per quintal for a crop in a district.
No SARIMAX forecasting — uses actual recorded prices directly.
"""

import json
import os

import pandas as pd

_MARKET_CSV = os.path.normpath(
    os.path.join(os.path.dirname(__file__), '..', '..', 'data', 'processed', 'market_prices_clean.csv')
)
_MAP_PATH = os.path.normpath(
    os.path.join(os.path.dirname(__file__), '..', '..', 'data', 'lookup', 'commodity_name_map.json')
)


def _load():
    try:
        df = pd.read_csv(_MARKET_CSV)
        df['district']  = df['district'].str.lower().str.strip()
        df['commodity'] = df['commodity'].str.lower().str.strip()
        with open(_MAP_PATH) as f:
            name_map = json.load(f)
        return df, name_map
    except Exception as e:
        return pd.DataFrame(), {}


_df, _name_map = _load()


def get_price(crop: str, district: str) -> dict | None:
    """
    Returns price data for a crop in a district.
    Tries district-specific price first, falls back to state-wide average.
    Returns None if no price data available for this crop.
    """
    if _df.empty:
        return None

    crop_lower = crop.lower().strip()
    commodity  = _name_map.get(crop_lower, crop_lower)
    dist_lower = district.lower().strip()

    # Filter by commodity
    rows = _df[_df['commodity'] == commodity]
    if rows.empty:
        return None

    # Try district-specific price first
    dist_rows = rows[rows['district'] == dist_lower]
    if dist_rows.empty:
        # Fall back to any district with this commodity
        dist_rows = rows

    row = dist_rows.iloc[0]

    return {
        'modal_price_per_kg':      round(float(row['modal_price_per_kg']), 2),
        'min_price_per_kg':        round(float(row['min_price_per_kg']), 2),
        'max_price_per_kg':        round(float(row['max_price_per_kg']), 2),
        'modal_price_per_quintal': round(float(row['modal_price_per_quintal']), 2),
        'district_used':           str(row['district']),
        'source':                  'Agmarknet',
        'date':                    str(row.get('arrivaldate', '')),
    }