"""
Tutorial: Using CurateClient for Data Transformation

This script demonstrates how to:
1. Link an existing .xdat recording.
2. Perform a transformation (e.g., 4x downsampling) with a real-time progress bar.
3. Verify the metadata of the resulting file.
"""

from pathlib import Path

from radiens_core.curate_client import CurateClient


def main():
    # --- CONFIGURATION (Change these to match your local setup) ---
    DATA_DIR = Path("path/to/your/data")
    INPUT_FILENAME = "recording_data.xdat"
    # --------------------------------------------------------------

    input_path = DATA_DIR / INPUT_FILENAME

    # Generate output name based on input
    # e.g., "recording_data.xdat" -> "recording_downsampled.xdat"
    base_stem = INPUT_FILENAME.replace("_data.xdat", "").replace(".xdat", "")
    output_name = f"{base_stem}_downsampled.xdat"
    output_path = DATA_DIR / output_name

    if not input_path.exists():
        print(f"Error: Input file not found at {input_path}")
        print("Please update DATA_DIR and INPUT_FILENAME in the script.")
        return

    print("--- Radiens CurateClient Tutorial ---")

    try:
        with CurateClient() as client:
            # 1. Link the data file
            print(f"Linking: {INPUT_FILENAME}")
            meta = client.link_data_file(input_path)
            print(f"  ID: {meta.id}")
            print(f"  Sampling Rate: {meta.time_range.fs} Hz")
            print(f"  Duration: {meta.time_range.dur_sec:.2f} seconds")

            # 2. Perform downsampling (4x)
            # This will automatically show a tqdm progress bar in your terminal.
            # NOTE: This will fail with a RadiensError if the output file already exists.
            print("\nStarting Downsampling (4x)...")
            new_meta = client.downsample(meta, factor=4, output_path=output_path)

            # 3. Verify results
            print("\nSuccess!")
            print(f"New File: {new_meta.path}/{new_meta.base_name}")
            print(f"New Sampling Rate: {new_meta.time_range.fs} Hz")
            print(f"New Duration: {new_meta.time_range.dur_sec:.2f} seconds")

    except Exception as e:
        print(f"\nError during curation: {e}")


if __name__ == "__main__":
    main()
