#!/usr/bin/env python3
"""
Stage 3c — Consolidate per-cell vectors_coordinates.csv files into a numbered
run folder under config/csv_exports/, ready for Stage 4.

Layout produced:
    config/csv_exports/N/cell_r{R}c{C}_full_vectors_coordinates.csv   (inputs)
    config/N/pair_coherence_composition.json                          (Stage 4 output)

N is the next free positive integer under config/csv_exports/.

Commands:
    --ingest <source_dir>        Bulk: copy & rename CSVs from a new run
                                 into the next numbered subfolder, and
                                 update cells_to_analyze.json to point
                                 at it.

    --label-map <json_file>      Optional: map arbitrary Stage 2 cell labels
                                 (for example A1, 01, north_west)
                                 to canonical row/column IDs.

    --source <csv_file> --cell rXcY [--run N]
                                 Single-cell: copy one
                                 vectors_coordinates.csv into the
                                 specified run folder (defaults to the
                                 highest-numbered existing run). Useful
                                 for accumulating cells one at a time as
                                 each JSX run completes.

    --reorganise-baseline        One-off: move the existing flat baseline
                                 CSVs into csv_exports/1/ and the existing
                                 pair_coherence_composition.json into
                                 config/1/.

Expected source layout for --ingest:
    <source_dir>/(r{ROW}c{COL} or c{COL}r{ROW})/Generated_Combinations/vectors_coordinates.csv
"""

from __future__ import annotations

import argparse
import json
import re
import shutil
import sys
from pathlib import Path
from typing import Optional

SCRIPT_DIR = Path(__file__).resolve().parent
CONFIG_DIR = SCRIPT_DIR.parent / "config"
CSV_EXPORTS_DIR = CONFIG_DIR / "csv_exports"
CONFIG_FILE = CONFIG_DIR / "cells_to_analyze.json"
LEGACY_OUTPUT_JSON = CONFIG_DIR / "pair_coherence_composition.json"

CELL_RC_RE = re.compile(r"^r(\d+)c(\d+)$", re.IGNORECASE)
CELL_CR_RE = re.compile(r"^c(\d+)r(\d+)$", re.IGNORECASE)


def normalize_cell_label(raw: str) -> tuple[str, int, int, bool]:
    """Normalize supported cell label formats to canonical `r{row}c{col}`.

    Returns (canonical_label, row, col, was_transposed_input).
    Supports both rNcM and cMrN inputs.
    """
    s = raw.strip().lower()
    m_rc = CELL_RC_RE.match(s)
    if m_rc:
        row, col = int(m_rc.group(1)), int(m_rc.group(2))
        return f"r{row}c{col}", row, col, False

    m_cr = CELL_CR_RE.match(s)
    if m_cr:
        col, row = int(m_cr.group(1)), int(m_cr.group(2))
        return f"r{row}c{col}", row, col, True

    raise ValueError(
        f"unsupported cell label {raw!r}; expected rNcM or cMrN (e.g. r1c1 or c1r1)"
    )


def load_label_map(path: Optional[str]) -> dict[str, str]:
    """Load label mapping JSON as {source_label: canonical_label}.

    Keys are matched case-insensitively after trim.
    Values are normalized to canonical rNcM using normalize_cell_label.
    """
    if not path:
        return {}

    p = Path(path).expanduser().resolve()
    if not p.exists():
        sys.exit(f"✗ label map file not found: {p}")

    try:
        with open(p) as f:
            data = json.load(f)
    except Exception as exc:
        sys.exit(f"✗ failed to read label map JSON {p}: {exc}")

    if not isinstance(data, dict):
        sys.exit("✗ label map must be a JSON object: {\"input_label\": \"r1c1\", ...}")

    loaded: dict[str, str] = {}
    for raw_key, raw_value in data.items():
        if not isinstance(raw_key, str) or not isinstance(raw_value, str):
            sys.exit("✗ label map keys and values must all be strings")
        key = raw_key.strip().lower()
        if not key:
            sys.exit("✗ label map contains an empty key")
        try:
            canonical, _, _, _ = normalize_cell_label(raw_value)
        except ValueError as exc:
            sys.exit(f"✗ invalid label map target for {raw_key!r}: {exc}")
        loaded[key] = canonical

    print(f"✓ Loaded label map: {p} ({len(loaded)} entries)")
    return loaded


def resolve_cell_label(raw: str, label_map: dict[str, str]) -> tuple[str, int, int, bool, bool]:
    """Resolve raw label to canonical rNcM.

    Returns:
      (canonical_label, row, col, was_transposed_input, used_map)
    """
    key = raw.strip().lower()
    if key in label_map:
        mapped = label_map[key]
        canonical, row, col, _ = normalize_cell_label(mapped)
        return canonical, row, col, False, True

    canonical, row, col, was_transposed = normalize_cell_label(raw)
    return canonical, row, col, was_transposed, False


def next_run_number() -> int:
    """Return the next free positive integer subfolder name under csv_exports/."""
    CSV_EXPORTS_DIR.mkdir(parents=True, exist_ok=True)
    used = set()
    for child in CSV_EXPORTS_DIR.iterdir():
        if child.is_dir() and child.name.isdigit():
            used.add(int(child.name))
    n = 1
    while n in used:
        n += 1
    return n


def highest_run_number() -> int | None:
    """Return the largest existing numbered subfolder under csv_exports/, or None."""
    if not CSV_EXPORTS_DIR.exists():
        return None
    nums = [int(c.name) for c in CSV_EXPORTS_DIR.iterdir()
            if c.is_dir() and c.name.isdigit()]
    return max(nums) if nums else None


def discover_cells(source: Path, label_map: dict[str, str]) -> list[tuple[str, int, int, Path]]:
    """Find cell folders under source containing vectors_coordinates.csv.

    Supports both rNcM and cMrN folder names.
    Returns list of (canonical_cell_label, row, col, csv_path), sorted by (row, col).
    """
    found: list[tuple[str, int, int, Path]] = []
    seen_by_cell: dict[str, Path] = {}
    transposed_count = 0
    mapped_count = 0
    if not source.exists():
        sys.exit(f"✗ source directory not found: {source}")
    for entry in source.iterdir():
        if not entry.is_dir():
            continue
        try:
            canonical_label, row, col, was_transposed, used_map = resolve_cell_label(entry.name, label_map)
        except ValueError:
            continue
        csv = entry / "Generated_Combinations" / "vectors_coordinates.csv"
        if not csv.exists():
            print(f"  ⚠ skipping {entry.name}: vectors_coordinates.csv not found at {csv}")
            continue
        if canonical_label in seen_by_cell:
            prev = seen_by_cell[canonical_label]
            sys.exit(
                "✗ duplicate cell mapping after normalization: "
                f"{entry.name!r} and {prev.parent.parent.name!r} both map to {canonical_label!r}"
            )
        seen_by_cell[canonical_label] = csv
        if used_map:
            mapped_count += 1
            print(f"  ⇢ mapped folder label {entry.name!r} -> {canonical_label!r}")
        if was_transposed:
            transposed_count += 1
            print(f"  ↻ normalizing folder label {entry.name!r} -> {canonical_label!r}")
        found.append((canonical_label, row, col, csv))
    found.sort(key=lambda x: (x[1], x[2]))
    if mapped_count:
        print(f"  ✓ mapped {mapped_count} label(s) via --label-map")
    if transposed_count:
        print(f"  ✓ normalized {transposed_count} transposed cell label(s) to canonical rNcM")
    return found


def update_config(csv_directory: str, selected_cells: list[str]) -> None:
    with open(CONFIG_FILE) as f:
        cfg = json.load(f)
    cfg["analysis_config"]["csv_directory"] = csv_directory
    cfg["analysis_config"]["selected_cells"] = selected_cells
    with open(CONFIG_FILE, "w") as f:
        json.dump(cfg, f, indent=2)
        f.write("\n")
    print(f"✓ Updated {CONFIG_FILE.name}:")
    print(f"    csv_directory = {csv_directory!r}")
    print(f"    selected_cells = {len(selected_cells)} cells")


def cmd_ingest(source_dir: str, label_map_path: Optional[str]) -> None:
    source = Path(source_dir).expanduser().resolve()
    print(f"Ingesting from: {source}")
    label_map = load_label_map(label_map_path)

    cells = discover_cells(source, label_map)
    if not cells:
        sys.exit("✗ no cell folders found with supported labels (rNcM or cMrN) and vectors_coordinates.csv")

    rows = sorted({r for _, r, _, _ in cells})
    cols = sorted({c for _, _, c, _ in cells})
    print(f"  Discovered {len(cells)} cells — grid: {len(rows)} rows × {len(cols)} cols")
    print(f"    rows: {rows}    cols: {cols}")

    n = next_run_number()
    dest_csv_dir = CSV_EXPORTS_DIR / str(n)
    dest_output_dir = CONFIG_DIR / str(n)

    if dest_csv_dir.exists() or dest_output_dir.exists():
        sys.exit(f"✗ refusing to overwrite existing folder(s): {dest_csv_dir} / {dest_output_dir}")

    dest_csv_dir.mkdir(parents=True)
    dest_output_dir.mkdir(parents=True)
    print(f"✓ Created run folders for run {n}:")
    print(f"    inputs : {dest_csv_dir.relative_to(CONFIG_DIR.parent)}")
    print(f"    output : {dest_output_dir.relative_to(CONFIG_DIR.parent)}")

    selected_cells: list[str] = []
    for label, _, _, src_csv in cells:
        dest_name = f"cell_{label}_full_vectors_coordinates.csv"
        dest_path = dest_csv_dir / dest_name
        shutil.copy2(src_csv, dest_path)
        selected_cells.append(label)
        print(f"  ✓ {label}: {src_csv.name}  →  {dest_name}")

    update_config(csv_directory=f"csv_exports/{n}", selected_cells=selected_cells)

    expected_grid = (4, 3)  # rows, cols hardcoded in 04_analyze_polygon_region_coherence.py
    actual_grid = (len(rows), len(cols))
    print()
    if actual_grid != expected_grid:
        print(
            f"⚠ Grid mismatch: ingested {actual_grid[0]} rows × {actual_grid[1]} cols, "
            f"but Stage 4 has GRID_ROWS={expected_grid[0]}, GRID_COLS={expected_grid[1]} hardcoded.\n"
            f"  Edit scripts/04_analyze_polygon_region_coherence.py before running Stage 4."
        )
    else:
        print(f"✓ Grid dims match Stage 4 defaults ({expected_grid[0]} rows × {expected_grid[1]} cols).")

    print()
    print(f"Run {n} ready. Next step: run Stage 4.")
    print(f"  python {SCRIPT_DIR.name}/04_analyze_polygon_region_coherence.py")


def cmd_source(csv_path: str, cell: str, run: int | None, label_map_path: Optional[str]) -> None:
    label_map = load_label_map(label_map_path)
    try:
        canonical_cell, _, _, was_transposed, used_map = resolve_cell_label(cell, label_map)
    except ValueError as exc:
        sys.exit(f"✗ {exc}")

    src = Path(csv_path).expanduser().resolve()
    if not src.exists():
        sys.exit(f"✗ source file not found: {src}")

    if run is None:
        run = highest_run_number()
        if run is None:
            sys.exit("✗ no existing run folders under csv_exports/. "
                     "Create one first with --ingest, or pass --run N explicitly.")
        print(f"Defaulting to highest existing run: {run}")

    dest_dir = CSV_EXPORTS_DIR / str(run)
    dest_dir.mkdir(parents=True, exist_ok=True)
    (CONFIG_DIR / str(run)).mkdir(parents=True, exist_ok=True)

    dest = dest_dir / f"cell_{canonical_cell}_full_vectors_coordinates.csv"
    if dest.exists():
        print(f"⚠ overwriting existing {dest.relative_to(CONFIG_DIR.parent)}")
    shutil.copy2(src, dest)

    with open(dest) as f:
        row_count = sum(1 for _ in f) - 1  # subtract header
    if used_map:
        print(f"  ⇢ mapped --cell {cell!r} -> {canonical_cell!r}")
    elif was_transposed:
        print(f"  ↻ normalized --cell {cell!r} -> {canonical_cell!r}")
    print(f"✓ {canonical_cell}: {row_count} vectors → {dest.relative_to(CONFIG_DIR.parent)}")


def cmd_reorganise_baseline() -> None:
    """Move the existing flat baseline files into the '1/' layout."""
    target_csv_dir = CSV_EXPORTS_DIR / "1"
    target_output_dir = CONFIG_DIR / "1"

    if target_csv_dir.exists():
        sys.exit(f"✗ {target_csv_dir} already exists — nothing to do.")

    # Find flat baseline CSVs sitting directly in csv_exports/
    flat_csvs = sorted(
        p for p in CSV_EXPORTS_DIR.glob("cell_r*c*_full_vectors_coordinates.csv") if p.is_file()
    )
    if not flat_csvs:
        sys.exit(f"✗ no flat baseline CSVs found in {CSV_EXPORTS_DIR}")

    print(f"Found {len(flat_csvs)} baseline CSVs in {CSV_EXPORTS_DIR.relative_to(CONFIG_DIR.parent)}")

    target_csv_dir.mkdir(parents=True)
    target_output_dir.mkdir(parents=True, exist_ok=True)

    for src in flat_csvs:
        dest = target_csv_dir / src.name
        shutil.move(str(src), str(dest))
        print(f"  ✓ moved {src.name}")

    if LEGACY_OUTPUT_JSON.exists():
        dest_json = target_output_dir / LEGACY_OUTPUT_JSON.name
        shutil.move(str(LEGACY_OUTPUT_JSON), str(dest_json))
        print(f"  ✓ moved {LEGACY_OUTPUT_JSON.name}  →  {dest_json.relative_to(CONFIG_DIR.parent)}")
    else:
        print(f"  ⚠ {LEGACY_OUTPUT_JSON.name} not found (skipped)")

    # Update config to point at the new location.
    with open(CONFIG_FILE) as f:
        cfg = json.load(f)
    cfg["analysis_config"]["csv_directory"] = "csv_exports/1"
    with open(CONFIG_FILE, "w") as f:
        json.dump(cfg, f, indent=2)
        f.write("\n")
    print(f"✓ Updated {CONFIG_FILE.name}: csv_directory = 'csv_exports/1'")
    print()
    print("Baseline reorganised as run 1. Existing CSVs and JSON now live in:")
    print(f"  {target_csv_dir.relative_to(CONFIG_DIR.parent)}/")
    print(f"  {target_output_dir.relative_to(CONFIG_DIR.parent)}/")


def main() -> None:
    parser = argparse.ArgumentParser(description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter)
    group = parser.add_mutually_exclusive_group(required=True)
    group.add_argument("--ingest", metavar="SOURCE_DIR",
                       help="Copy & rename vectors_coordinates.csv files from per-cell folders "
                            "under SOURCE_DIR into the next numbered run folder.")
    group.add_argument("--source", metavar="CSV_PATH",
                       help="Single-cell: path to one vectors_coordinates.csv to import. "
                            "Requires --cell rXcY.")
    group.add_argument("--reorganise-baseline", action="store_true",
                       help="One-off: move existing flat baseline files into '1/'.")
    parser.add_argument("--cell", metavar="CELL",
                        help="Cell ID for --source; accepts rXcY or cYrX (e.g. r1c1, c1r1).")
    parser.add_argument("--run", type=int, metavar="N",
                        help="Run number for --source (defaults to highest existing).")
    parser.add_argument("--label-map", metavar="JSON_PATH",
                        help="Optional JSON map of source labels to canonical cells, "
                             "e.g. {'A1': 'r1c1', 'NW': 'r1c1'}")
    args = parser.parse_args()

    if args.ingest:
        cmd_ingest(args.ingest, args.label_map)
    elif args.source:
        if not args.cell:
            parser.error("--source requires --cell rXcY")
        cmd_source(args.source, args.cell, args.run, args.label_map)
    elif args.reorganise_baseline:
        cmd_reorganise_baseline()


if __name__ == "__main__":
    main()
