"""Read one Rosstat monthly file of average consumer prices by federal subject (sred_potreb_cen_MM-YYYY.xlsx).
Each file holds one sheet per month of the year up to MM, named 'MM(YYYY)'. Row 4 carries the item codes and
data start on row 6; the first row that names a subject is the subject itself (rows for its cities follow)."""
import io, os, re, sys
sys.path.insert(0, os.path.join(os.path.dirname(os.path.abspath(__file__)), '..', 'pipeline'))
sys.path.insert(0, os.path.dirname(os.path.abspath(__file__)))
from match import match_region

SERIES = {'9419': 'rs-rent1', '9421': 'rs-rent2', '9218': 'rs-transit', '9513': 'rs-kinder', '9444': 'rs-water', '9449': 'rs-heat', '9471': 'rs-power',
          '9921': 'rs-school-private', '9941': 'rs-uni-private', '9942': 'rs-uni-public', '9711': 'rs-doctor', '9761': 'rs-dentist', '9796': 'rs-filling', '9714': 'rs-bloodtest'}

def num(c):
    if c in (None, '', '-', '…', '...', 'x', 'х') or not re.match(r'^-?[\d\s.,]+$', str(c)): return None
    return float(str(c).replace(' ', '').replace(',', '.'))

def parse(b):
    """-> {(period, region, series): value}, [periods]"""
    import openpyxl
    wb = openpyxl.load_workbook(io.BytesIO(b), read_only=True, data_only=True)
    out, periods = {}, []
    for ws in wb.worksheets:
        m = re.match(r'^(\d\d)\((20\d\d)\)$', ws.title.strip())
        if not m: continue
        period = f'{m.group(2)}-{m.group(1)}'; periods.append(period)
        it = ws.iter_rows(values_only=True); hdr = [next(it, None) for _ in range(5)]
        codes = [str(c).strip() if c is not None else '' for c in (hdr[3] or [])]
        cols = {SERIES[c]: i for i, c in enumerate(codes) if c in SERIES}
        seen = set()
        for r in it:
            if not r or len(r) < 2 or not isinstance(r[1], str): continue
            rid = match_region(r[1])
            if not rid or rid in seen: continue
            seen.add(rid)
            for s, i in cols.items():
                v = num(r[i]) if i < len(r) else None
                if v: out[(period, rid, s)] = round(v, 2)
    return out, sorted(periods)
