#!/usr/bin/env python3
"""
MCRO JSON reorganizer
=====================

Scan a directory of MCRO JSON files and copy them into a new directory
structure organized by case_id, with filenames based on the "filename"
field in the JSON (but with a .json extension).

RESULTING LAYOUT
----------------

For each input JSON:

  - Read:
      case.case_id
      filename

  - Write a copy of the JSON text to:

      <outdir>/<case_id>/<filename-with-.json-extension>

  Example:

      Input JSON:
        doc path:      .../documents/a0796f7d....json
        case.case_id:  "27-CR-23-1886"
        filename:      "MCRO_27-CR-23-1886_Order-Other_2023-05-12_20240430072904.pdf"

      Output JSON:
        <outdir>/27-CR-23-1886/MCRO_27-CR-23-1886_Order-Other_2023-05-12_20240430072904.json

If case_id is missing, the file is placed under "NO_CASE_ID".
If filename is missing, we fall back to the original JSON basename.

We *copy* the original JSON text (no re-serialization), so formatting is preserved.

USAGE
=====

  python3 mcro_json_reorganize_by_case.py \
      --input  /path/to/json/documents \
      --output /path/to/reorganized_json_by_case \
      [--pattern "*.json"] \
      [--recurse]

"""

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


def derive_new_name_from_filename(filename_field: str) -> str:
    """
    Turn the JSON 'filename' field into a .json basename.
    If it already has an extension, replace it with .json.
    Otherwise, just append .json.
    """
    if not filename_field:
        return "UNKNOWN.json"

    # Strip any surrounding whitespace just in case
    filename_field = filename_field.strip()

    # If there's a dot, replace the extension
    if "." in filename_field:
        stem = ".".join(filename_field.split(".")[:-1])
        return stem + ".json"
    else:
        return filename_field + ".json"


def main():
    ap = argparse.ArgumentParser(description="Reorganize MCRO JSON files by case_id and filename.")
    ap.add_argument(
        "--input",
        required=True,
        help="Directory containing the original JSON files.",
    )
    ap.add_argument(
        "--output",
        required=True,
        help="Root directory where reorganized JSONs will be written.",
    )
    ap.add_argument(
        "--pattern",
        default="*.json",
        help='Glob pattern for JSON files (default: "*.json")',
    )
    ap.add_argument(
        "--recurse",
        action="store_true",
        help="Recurse into subdirectories under --input.",
    )
    args = ap.parse_args()

    in_dir = Path(args.input)
    out_root = Path(args.output)

    if not in_dir.is_dir():
        print(f"[error] Input directory does not exist or is not a directory: {in_dir}", file=sys.stderr)
        sys.exit(1)

    if args.recurse:
        files = sorted(in_dir.rglob(args.pattern))
    else:
        files = sorted(in_dir.glob(args.pattern))

    if not files:
        print(f"[warn] No files matched pattern {args.pattern} under {in_dir}", file=sys.stderr)
        sys.exit(0)

    out_root.mkdir(parents=True, exist_ok=True)

    n_ok = 0
    n_skip = 0

    for src in files:
        try:
            # Read original text once so we can both parse and copy exactly
            text = src.read_text(encoding="utf-8")
            data = json.loads(text)
        except Exception as e:
            print(f"[warn] Skipping {src}: failed to read/parse JSON ({e})", file=sys.stderr)
            n_skip += 1
            continue

        if not isinstance(data, dict):
            print(f"[warn] Skipping {src}: JSON root is not an object", file=sys.stderr)
            n_skip += 1
            continue

        # Extract case_id
        case = data.get("case") or {}
        case_id = (case.get("case_id") or "").strip()
        if not case_id:
            case_id = "NO_CASE_ID"

        # Extract filename field
        filename_field = (data.get("filename") or "").strip()
        if not filename_field:
            # fall back to original JSON basename if filename missing
            filename_field = src.stem

        new_basename = derive_new_name_from_filename(filename_field)

        # Build destination path
        dest_dir = out_root / case_id
        dest_dir.mkdir(parents=True, exist_ok=True)

        dest_path = dest_dir / new_basename

        try:
            dest_path.write_text(text, encoding="utf-8")
            n_ok += 1
        except Exception as e:
            print(f"[warn] Failed to write {dest_path}: {e}", file=sys.stderr)
            n_skip += 1

    print(f"[ok] Finished reorganizing JSONs.")
    print(f"     Source directory : {in_dir.resolve()}")
    print(f"     Output root      : {out_root.resolve()}")
    print(f"     Files processed  : {len(files)}")
    print(f"     Files copied     : {n_ok}")
    print(f"     Files skipped    : {n_skip}")


if __name__ == "__main__":
    main()
