from __future__ import annotations

import csv
import glob
import os

from osgeo import gdal

from .config import Config
from .gdal_utils import build_vrt, ensure_dir, ensure_parent, open_dataset

gdal.UseExceptions()


def export_orthophotos(cfg: Config, *, force_vrt: bool = False) -> int:
    ensure_dir(cfg.work.work_dir)
    ensure_dir(cfg.export.ortho_dir)
    ensure_parent(cfg.work.ortho_vrt)

    jp2_paths = sorted(glob.glob(os.path.join(cfg.raw.dop20_dir, "*.jp2")))
    if not jp2_paths:
        raise SystemExit(f"No JP2 files found in {cfg.raw.dop20_dir}. Run scripts/dlscript_dop20.sh first.")

    build_vrt(cfg.work.ortho_vrt, jp2_paths, force=force_vrt)
    vrt_ds = open_dataset(cfg.work.ortho_vrt, f"Could not open VRT at {cfg.work.ortho_vrt}")

    if not os.path.exists(cfg.export.manifest_path):
        raise SystemExit(f"Tile index missing: {cfg.export.manifest_path}. Run heightmap export first.")

    with open(cfg.export.manifest_path, newline="", encoding="utf-8") as f:
        reader = csv.DictReader(f)
        written = 0
        skipped = 0

        for row in reader:
            try:
                tile_id = row["tile_id"]
                xmin = float(row["xmin"])
                ymin = float(row["ymin"])
                xmax = float(row["xmax"])
                ymax = float(row["ymax"])
            except (KeyError, ValueError) as exc:
                print(f"Skipping malformed row {row}: {exc}")
                skipped += 1
                continue

            out_path = os.path.join(cfg.export.ortho_dir, f"{tile_id}.jpg")
            opts = gdal.TranslateOptions(
                format="JPEG",
                width=cfg.ortho.out_res,
                height=cfg.ortho.out_res,
                projWin=(xmin, ymax, xmax, ymin),
                creationOptions=[f"QUALITY={cfg.ortho.jpeg_quality}", "WORLDFILE=YES"],
            )
            try:
                gdal.Translate(out_path, vrt_ds, options=opts)
            except RuntimeError as exc:
                print(f"Translate failed for {tile_id}: {exc}")
                skipped += 1
                continue

            written += 1
            print(f"Wrote {out_path}")

    print(f"Summary: wrote {written} orthophoto tiles; skipped {skipped}.")
    return 1 if skipped else 0
