"""
GLAMBIE fixed-geometry monthly specific MB run.

Environment variables (all required):
  OGGM_WORKDIR   – scratch working directory for OGGM
  OGGM_OUTDIR    – root output directory; a sub-directory RGI{reg} is created
  OGGM_RGI_REG   – two-digit GTN-G / RGI region (01–19)
"""
import logging
import os

import geopandas as gpd
from oggm import cfg, utils, workflow

from glambie_helper import (
    compile_fixed_geometry_specific_mb_region,
    fixed_geometry_specific_mb_ts,
)

# ---------------------------------------------------------------------------
# Environment
# ---------------------------------------------------------------------------
WORKING_DIR = os.environ.get("OGGM_WORKDIR", "")
if not WORKING_DIR:
    raise RuntimeError("Set OGGM_WORKDIR")
WORKING_DIR = utils.mkdir(WORKING_DIR)

OUTPUT_DIR = os.environ.get("OGGM_OUTDIR", "")
if not OUTPUT_DIR:
    raise RuntimeError("Set OGGM_OUTDIR")

rgi_reg = os.environ.get("OGGM_RGI_REG", "")
if rgi_reg not in [f"{r:02d}" for r in range(1, 20)]:
    raise RuntimeError("Set OGGM_RGI_REG to a two-digit region code (01–19)")

OUTPUT_DIR = utils.mkdir(OUTPUT_DIR)
GLACIER_DIR = utils.mkdir(os.path.join(OUTPUT_DIR, "per_glacier", f"RGI{rgi_reg}"))

# ---------------------------------------------------------------------------
# OGGM configuration
# ---------------------------------------------------------------------------
cfg.initialize(logging_level="INFO")
cfg.PARAMS["use_multiprocessing"] = True
cfg.PARAMS["continue_on_error"] = True
cfg.PATHS["working_dir"] = WORKING_DIR

log = logging.getLogger(__name__)
log.workflow(f"Starting GLAMBIE fixed-geometry run for RGI region {rgi_reg}")
utils.show_versions(logger=log)

# ---------------------------------------------------------------------------
# Glacier list
# ---------------------------------------------------------------------------
rgi_ids = gpd.read_file(utils.get_rgi_region_file(rgi_reg, version="62"))

# Greenland: skip peripheral glaciers connected at level 2
if rgi_reg == "05":
    rgi_ids = rgi_ids.loc[rgi_ids["Connect"] != 2]

log.workflow(f"Number of glaciers: {len(rgi_ids)}")

# ---------------------------------------------------------------------------
# Glacier directories from the 2025.6 ERA5 per-glacier spinup pre-processing
# ---------------------------------------------------------------------------
base_url = (
    "https://cluster.klima.uni-bremen.de/~oggm/gdirs/oggm_v1.6/"
    "L3-L5_files/2025.6/elev_bands/ERA5/per_glacier_spinup/"
)
gdirs = workflow.init_glacier_directories(
    rgi_ids,
    prepro_base_url=base_url,
    from_prepro_level=3,
    prepro_border=80,
)

# ---------------------------------------------------------------------------
# Per-glacier fixed-geometry monthly specific MB  (1975-01 to 2025-12)
# Files land in GLACIER_DIR/batch_XXXX/RGI60-XX.XXXXX.nc
# ---------------------------------------------------------------------------
workflow.execute_entity_task(
    fixed_geometry_specific_mb_ts,
    gdirs,
    y0=1975,
    y1=2025,
    glacier_dir=GLACIER_DIR,
)

# ---------------------------------------------------------------------------
# Regional aggregation  → OUTPUT_DIR/region_specific_mb.nc
# ---------------------------------------------------------------------------
compile_fixed_geometry_specific_mb_region(
    y0=1975,
    y1=2025,
    outdir=OUTPUT_DIR,
    glacier_dir=GLACIER_DIR,
)

log.workflow("GLAMBIE fixed-geometry run complete.")
