

import surfa as sf

ct = sf.load_volume('0/ct.nii.gz')
clipped = ct.clip(0, 80)
clipped.save('0/clipped.nii.gz')

exit()


from typing import Optional

import os

import SimpleITK as sitk

from pyradise.data import (Subject, IntensityImage, SegmentationImage,
                           Modality, Organ, Annotator)
from pyradise.fileio.extraction import SimpleModalityExtractor
import pyradise.data as ps_data
import pyradise.fileio as ps_io

# from nii_to_dicom import convert_subject_to_dicom_rtss

DCM_CT = '/nn/7295866/20250127/CT/a'
label_file = '/nn/7295866/20250127/output/processed_7_3D_SAG_T1_MPRAGE_+C_20250127132612.nii.gz'


segdir = '/nn/7295866/20250127/seg'
os.makedirs(segdir, exist_ok=True)

output_dir_path = '/nn/7295866/20250127/pyradise'
os.makedirs(output_dir_path, exist_ok=True)

rtss_file = '/nn/7295866/20250127/CT/a-rtss2.dcm'


class ExampleModalityExtractor(ps_io.ModalityExtractor):

    def extract_from_dicom(self,
                           path: str
                           ) -> Optional[ps_data.Modality]:
        # Extract the necessary attributes from the DICOM file
        tags = (ps_io.Tag((0x0008, 0x0060)),  # Modality
                ps_io.Tag((0x0008, 0x103e)))  # Series Description
        dataset_dict = self._load_dicom_attributes(tags, path)

        # Identify the modality rule-based
        modality = dataset_dict.get('Modality', {}).get('value', None)
        series_desc = dataset_dict.get('Series Description', {}).get('value', '')
        if modality == 'MR':
            if 't1' in series_desc.lower():
                return ps_data.Modality('T1')
            elif 't2' in series_desc.lower():
                return ps_data.Modality('T2')
            else:
                return None
        elif modality == 'CT':
            return ps_data.Modality('CT')
        else:
            return None

    def extract_from_path(self,
                          path: str
                          ) -> Optional[ps_data.Modality]:
        
        if 'CT' in path:
            return ps_data.Modality('CT')
        
        # Identify the discrete image file's modality rule-based
        filename = os.path.basename(path)

        # Check if the image contains an img prefix
        # (i.e., it is a intensity image)
        if not filename.startswith('img'):
            return None

        # Check if the image contains a modality search string
        if 'T1' in filename:
            return ps_data.Modality('T1')
        elif 'T2' in filename:
            return ps_data.Modality('T2')
        else:
            return None



reader = sitk.ImageSeriesReader()
dicom_names = reader.GetGDCMSeriesFileNames(DCM_CT)
reader.SetFileNames(dicom_names)
reader.MetaDataDictionaryArrayUpdateOn()
reader.LoadPrivateTagsOn()
image = reader.Execute()


final_image = sitk.ReadImage(label_file)
final_image = sitk.Resample(
    final_image, 
    image, 
    sitk.Transform(), 
    sitk.sitkNearestNeighbor
)

lss = sitk.LabelShapeStatisticsImageFilter()
lss.Execute(final_image)

images = []
images.append(IntensityImage(image, Modality('CT')))


for label in lss.GetLabels():
    segfile = os.path.join(segdir, 'seg-%d.nii.gz'%label)
    print(segfile)
#     sitk.WriteImage(final_image==label, segfile)
    images.append(SegmentationImage(final_image==label, str(label)))
    
subject = Subject('7295866', images)       

dcm_crawler = ps_io.SubjectDicomCrawler(DCM_CT,
#                                         modality_extractor=SimpleModalityExtractor(['CT']),
                                        modality_extractor=ExampleModalityExtractor(),
                                       )
dicom_series_info = dcm_crawler.execute()

print(dicom_series_info[0])
print(dicom_series_info[0].get_modality())
print(dicom_series_info[0].get_path())
print(dicom_series_info[0].get_patient_id())
print(dicom_series_info[0].get_patient_name())


# exit()

reference_modality = 'CT'

use_3d_conversion = True
if use_3d_conversion:
    conv_conf = ps_io.RTSSConverter3DConfiguration()
else:
    conv_conf = ps_io.RTSSConverter2DConfiguration()

    
meta_data = ps_io.RTSSMetaData(
#     patient_size='180',
#     patient_weight='80',
#     patient_age='050Y',
    series_description='Converted from NIfTI')
    
    
converter = ps_io.SubjectToRTSSConverter(subject,
                                         dicom_series_info,
                                         reference_modality,
                                         conv_conf,
                                         meta_data)
rtss = converter.convert()


# Write the DICOM-RTSS to a separate subject directory
# and include the DICOM files crawled before
# Note: If you want to output just a subset of the
# original DICOM files you may use additional selectors

writer = ps_io.DicomSeriesSubjectWriter()
rtss_filename = rtss_file
rtss_combination = ((rtss_filename, rtss),)

writer.write(rtss_combination, output_dir_path,
             subject.get_name(), dicom_series_info)


'''
pip install git+https://github.com/adalca/neurite.git git+https://github.com/freesurfer/surfa.git git+https://github.com/voxelmorph/voxelmorph.git



mri_synthmorph/mri_synthmorph '/nn/7295866/20250127/output/processed_7_3D_SAG_T1_MPRAGE_+C_20250127132612.nii.gz'  -m affine -t trans.lta -o out-aff.nii.gz moving.nii.gz clipped.nii.gz -g


time FREESURFER_HOME=/123/onlylian/mri_synthmorph mri_synthmorph/mri_synthmorph -m affine -t trans.lta -o out-aff.nii.gz '/nn/7295866/20250127/nii/a_1.1_CyberKnife_head(MAR)_20250127111447_5.nii.gz' '/nn/7295866/20250127/nii/7_3D_SAG_T1_MPRAGE_+C_20250127132612_100.nii.gz' -g


###models
wget https://surfer.nmr.mgh.harvard.edu/docs/synthmorph/synthmorph.affine.2.h5
wget https://surfer.nmr.mgh.harvard.edu/docs/synthmorph/synthmorph.deform.3.h5
wget https://surfer.nmr.mgh.harvard.edu/docs/synthmorph/synthmorph.rigid.1.h5

time FREESURFER_HOME=/123/onlylian/mri_synthmorph mri_synthmorph/mri_synthmorph -m affine -t trans.lta -o out-aff.nii.gz t1c.nii.gz ct.nii.gz -g

time FREESURFER_HOME=/123/onlylian/mri_synthmorph mri_synthmorph/mri_synthmorph -m affine -t 0/trans.lta -o 0/out-aff.nii.gz 0/t1c.nii.gz 0/clipped.nii.gz -g
time FREESURFER_HOME=/123/onlylian/mri_synthmorph mri_synthmorph/mri_synthmorph -o 0/out.nii.gz 0/t1c.nii.gz 0/clipped.nii.gz -g

'''