#!/usr/bin/env python3
"""
Rename *_CTDadjusted.nc files to *_adjusted.nc

Features
--------
- Works across all deployments/missions
- Optional filter by deployment or mission
- Handles both L0-timeseries and L0-gridfiles
- Skips safely if target already exists
"""

from pathlib import Path
import sys

# ================= ROOT DIRECTORY =================
ROOT = Path("/mounts/cproofdata/processing/deployments")
# ================= FUNCTIONS =================
def rename_netcdf(nc_path: Path):
    try:
        if "_CTDadjusted.nc" not in nc_path.name:
            return

        new_name = nc_path.name.replace("_CTDadjusted.nc", "_adjusted.nc")
        new_path = nc_path.with_name(new_name)

        # Avoid overwriting existing files
        if new_path.exists():
            print(f"    ⚠️  Exists, skipping: {new_name}")
            return

        nc_path.rename(new_path)
        print(f"    🔁 {nc_path.name} → {new_name}")

    except Exception as e:
        print(f"    ❌ Failed {nc_path.name}: {e}")


def process_mission_dir(mission_dir: Path):
    print(f"  📁 {mission_dir.name}")

    for sub in ["L0-timeseries", "L0-gridfiles"]:
        nc_dir = mission_dir / sub
        if not nc_dir.exists():
            continue

        for nc in sorted(nc_dir.glob("*_CTDadjusted.nc")):
            rename_netcdf(nc)


def main():
    # Optional filter: deployment OR mission
    target = sys.argv[1] if len(sys.argv) == 2 else None

    if len(sys.argv) > 2:
        print("Usage: python rename_adjusted.py [deployment | mission]")
        sys.exit(1)

    for deployment_dir in sorted(ROOT.iterdir()):
        if not deployment_dir.is_dir():
            continue

        deployment = deployment_dir.name

        for mission_dir in sorted(deployment_dir.iterdir()):
            if not mission_dir.is_dir():
                continue

            mission_name = mission_dir.name

            # Apply filter
            if target and mission_name != target and deployment != target:
                continue

            print(f"\n🚀 Processing {deployment}")
            process_mission_dir(mission_dir)


if __name__ == "__main__":
    main()