import csv
from collections import OrderedDict

metrics = {
    "longest_pause_duration": "2,440ms",
    "overall_max_hr": "163 bpm",
    "slowest_vt_start_time": "Day 2 / 01:25:06",
    "overall_max_hr_bpm": "163",
    "sinus_tachy_total_time_in_millis": "219848",
    "afib_min_rr_in_millis": "331",
    "svt_avg_rr_in_millis": "405",
    "longest_nsr_duration": "00:06:43",
    "sveb_bigeminy_burden": "0.09%",
    "overall_nn_count": "1364",
    "total_monitor_time_in_millis": "82140000",
    "fastest_svt_average_hr_in_bpm": "165",
    "vt_has_patient_diary_events_count": "0",
    "tachy_has_patient_triggered_events_count": "0",
    "vt_total_time": "00:03:07",
    "slowest_vt_duration": "00:00:10",
    "brady_has_patient_triggered_events_count": "0",
    "overall_nn_length_in_millis": "854428",
    "vt_total_time_in_millis": "187576",
    "veb_bigeminy_burden": "<0.01%",
    "veb_couplet_total_time": "00:00:58",
    "sveb_bigeminy_beats_count": "126",
    "unclassified_events_count": "0",
    "veb_couplet_episodes": "58",
    "ivr_total_time": "1,976ms",
    "total_analysis_time_in_millis": "82140000",
    "sveb_isolated_count": "3474",
    "beats_count": "133513",
    "sinus_average_hr": "96 bpm",
    "longest_svt_max_hr": "161 bpm",
    "av_block_2nd_degree_count": "0",
    "veb_isolated_count": "2603",
    "svt_burden": "0.01%",
    "longest_svt_beats_count": "5 beats",
    "slowest_vt_min_hr": "70 bpm",
    "test_start_time_in_epoch_millis": "1694796840000",
    "sveb_trigeminy_episodes": "52",
    "veb_trigeminy_episodes": "2",
    "sinus_brady_total_time": "0ms",
    "total_monitor_time": "22:49:00",
    "ivr_beats_count": "3",
    "sveb_count": "3947",
    "av_block_total_time": "0",
    "longest_afib_start_time_in_millis": "1694811210000",
    "pause_burden": "<0.01%",
    "slowest_vt_duration_in_millis": "10580",
    "longest_pause_start_time_in_epoch_millis": "1694806092180",
    "sveb_burden": "2.96%",
    "afib_avg_hr_in_bpm": "98",
    "sinus_has_patient_triggered_events_count": "0",
    "sveb_couplet_episodes": "83",
    "sveb_in_patient_diary_events_count": "0",
    "sinus_max_hr": "115 bpm",
    "min_nn_time_in_epoch_millis": "1694796861220",
    "afib_burden": "98.9%",
    "fastest_vt_max_hr": "183 bpm",
    "veb_trigeminy_beats_count": "7",
    "artifacts_total_time": "0ms",
    "afib_total_time": "22:33:45",
    "total_analysis_time": "22:49:00",
    "veb_couplet_beats_count": "116",
    "sinus_tachy_total_time": "00:03:39",
    "test_end_time_in_epoch_millis": "1694878980000",
    "overall_min_hr_time": "Day 2 / 06:10:38",
    "av_block_3rd_degree_count": "0",
    "vt_burden": "0.23%",
    "sveb_trigeminy_beats_count": "166",
    "longest_pause_duration_in_millis": "2440",
    "pause_has_patient_diary_events_count": "0",
    "nsr_count": "7",
    "min_rr_length_in_millis": "368",
    "sveb_couplet_total_time": "00:01:27",
    "veb_bigeminy_beats_count": "13",
    "veb_trigeminy_total_time": "9,672ms",
    "max_nn_length_in_millis": "769",
    "max_rr_length_in_millis": "1034",
    "other_beats_count": "0",
    "sinus_min_hr_bpm": "78",
    "total_artifacts_time_in_millis": "0",
    "svt_max_hr_in_bpm": "174",
    "longest_nsr_start_time_in_epoch_millis": "1694810554972",
    "afib_avg_rr_in_millis": "615",
    "afib_max_rr_in_millis": "1203",
    "av_block_burden": "0%",
    "af_has_patient_diary_events_count": "0",
    "fastest_vt_average_hr_in_bpm": "183",
    "slowest_vt_average_hr_in_bpm": "92",
    "sinus_max_hr_time_in_millis": "1694796861220",
    "sinus_min_hr_time_in_millis": "1694810563972",
    "sveb_in_patient_events_count": "0",
    "fastest_svt_average_hr": "165 bpm",
    "patient_events_count": "0",
    "longest_svt_duration": "2,300ms",
    "fastest_vt_start_time": "Day 2 / 00:45:29",
    "sinus_tachy_burden_value": "0.267650",
    "vt_count": "32",
    "vt_has_patient_events_count": "0",
    "svt_avg_hr_in_bpm": "148",
    "overall_rr_count": "133492",
    "longest_vt_average_hr": "101 bpm",
    "sveb_isolated_burden": "2.60%",
    "afib_max_hr_in_bpm": "181",
    "sinus_tachy_burden": "0.27%",
    "longest_afib_start_time": "Day 1 / 16:53:30",
    "fastest_svt_start_time": "Day 2 / 04:00:22",
    "sinus_beat_count": "126428",
    "sinus_average_hr_bpm": "96",
    "predominate_rhythm_duration": "22:33:45",
    "longest_vt_duration_in_millis": "61820",
    "sinus_brady_count": "0",
    "sveb_in_patient_triggered_events_count": "0",
    "tachy_has_patient_events_count": "0",
    "af_has_patient_triggered_events_count": "0",
    "sinus_brady_total_time_in_millis": "0",
    "veb_trigeminy_burden": "<0.01%",
    "longest_vt_max_hr": "155 bpm",
    "longest_svt_max_hr_in_bpm": "161",
    "fastest_afib_start_time": "Day 2 / 00:32:27",
    "longest_afib_duration": "18:49:30",
    "fastest_vt_duration_in_millis": "1192",
    "svt_has_patient_diary_events_count": "0",
    "longest_afib_hr_in_bpm": "97",
    "longest_svt_average_hr": "152 bpm",
    "sinus_has_patient_events_count": "0",
    "longest_vt_start_time": "Day 2 / 01:25:33",
    "vt_beats_count": "393",
    "sinus_brady_burden": "0%",
    "overall_min_hr": "58 bpm",
    "sinus_has_patient_diary_events_count": "0",
    "av_block_count": "0",
    "fastest_svt_max_hr_in_bpm": "174",
    "longest_vt_start_time_in_millis": "1694841933896",
    "veb_bigeminy_episodes": "4",
    "svt_min_rr_in_millis": "344",
    "overall_average_hr_bpm": "98",
    "test_start_time": "09/15/2023 12:54:00",
    "patient_triggered_events_count": "0",
    "longest_svt_average_hr_in_bpm": "152",
    "sveb_couplet_beats_count": "166",
    "fastest_vt_beats_count": "3 beats",
    "nsr_total_time": "00:11:16",
    "fastest_svt_beats_count": "3 beats",
    "nsr_burden": "0.82%",
    "overall_average_hr": "98 bpm",
    "longest_svt_duration_in_millis": "2300",
    "longest_vt_average_hr_in_bpm": "101",
    "longest_svt_start_time": "Day 2 / 02:42:42",
    "sinus_tachy_count": "7",
    "fastest_afib_start_time_in_millis": "1694838747000",
    "min_nn_length_in_millis": "522",
    "brady_has_patient_events_count": "0",
    "veb_in_patient_diary_events_count": "0",
    "slowest_vt_min_hr_in_bpm": "70",
    "longest_vt_max_hr_in_bpm": "155",
    "unclassified_events_total_time": "0ms",
    "vt_has_patient_triggered_events_count": "0",
    "fastest_afib_duration": "10,000ms",
    "overall_max_hr_time_in_millis": "1694838747852",
    "svt_beats_count": "20",
    "veb_isolated_burden": "1.95%",
    "slowest_vt_start_time_in_millis": "1694841906208",
    "pause_has_patient_triggered_events_count": "0",
    "sinus_brady_burden_value": "0.000000",
    "svt_has_patient_events_count": "0",
    "patient_diary_events_count": "0",
    "max_rr_time_in_epoch_millis": "1694859038852",
    "veb_burden": "2.35%",
    "slowest_vt_average_hr": "92 bpm",
    "veb_in_patient_triggered_events_count": "0",
    "sinus_min_hr": "78 bpm",
    "overall_min_hr_bpm": "58",
    "predominate_rhythm": "Atrial Rhythm",
    "svt_has_patient_triggered_events_count": "0",
    "pause_has_patient_events_count": "0",
    "test_duration_in_millis": "82140000",
    "veb_couplet_burden": "0.09%",
    "fastest_svt_max_hr": "174 bpm",
    "fastest_vt_start_time_in_millis": "1694839529736",
    "sinus_beat_burden": "94.7%",
    "fastest_vt_duration": "1,192ms",
    "artifacts_burden": "0%",
    "min_rr_time_in_epoch_millis": "1694838747852",
    "afib_min_hr_in_bpm": "50",
    "fastest_afib_hr": "163 bpm",
    "fastest_vt_average_hr": "183 bpm",
    "artifacts_count": "0",
    "sinus_max_hr_bpm": "115",
    "longest_svt_start_time_in_millis": "1694846562108",
    "fastest_vt_max_hr_in_bpm": "183",
    "sveb_trigeminy_burden": "0.12%",
    "svt_max_rr_in_millis": "516",
    "test_end_time": "09/16/2023 11:43:00",
    "ivr_episodes": "1",
    "test_duration": "22:49:00",
    "svt_min_hr_in_bpm": "116",
    "afib_count": "469",
    "longest_nsr_start_time": "Day 1 / 16:42:34",
    "other_beats_burden": "0%",
    "longest_vt_duration": "00:01:01",
    "svt_total_time": "9,068ms",
    "veb_count": "3138",
    "sveb_trigeminy_total_time": "00:05:47",
    "longest_vt_beats_count": "104 beats",
    "overall_max_hr_time": "Day 2 / 00:32:27",
    "sinus_min_hr_time": "Day 1 / 16:42:43",
    "overall_rr_length_in_millis": "82134264",
    "pause_count": "1",
    "brady_has_patient_diary_events_count": "0",
    "fastest_svt_duration": "1,156ms",
    "longest_nsr_duration_in_millis": "403256",
    "veb_in_patient_events_count": "0",
    "sveb_couplet_burden": "0.12%",
    "fastest_svt_duration_in_millis": "1156",
    "overall_min_hr_time_in_millis": "1694859038852",
    "svt_total_time_in_millis": "9068",
    "pause_total_time": "2,440ms",
    "longest_pause_start_time": "Day 1 / 15:28:12",
    "max_nn_time_in_epoch_millis": "1694810563972",
    "slowest_vt_beats_count": "16 beats",
    "sinus_max_hr_time": "Day 1 / 12:54:21",
    "longest_afib_hr": "97 bpm",
    "tachy_has_patient_diary_events_count": "0",
    "sveb_bigeminy_total_time": "00:02:48",
    "svt_count": "6",
    "fastest_svt_start_time_in_millis": "1694851222992",
    "af_has_patient_events_count": "0",
    "afib_burden_value": "98.886436",
    "longest_afib_duration_in_millis": "67770000",
    "sveb_bigeminy_episodes": "36",
    "veb_bigeminy_total_time": "00:00:12"
  }

findings_used_metrics_keys = [
    # Basic monitoring information
    'test_start_time',
    'test_duration',
    
    # Predominant rhythm
    'predominate_rhythm',
    
    # Heart rate information
    'overall_max_hr',
    'overall_max_hr_time',
    'overall_min_hr',
    'overall_min_hr_time',
    'overall_average_hr',
    
    # Pause information
    'pause_count',
    'longest_pause_duration',
    'longest_pause_start_time',
    
    # Ventricular Ectopic Beats (VEB)
    'veb_isolated_count',
    'veb_isolated_burden',
    'veb_couplet_episodes',
    'veb_couplet_burden',
    'veb_bigeminy_episodes',
    'veb_bigeminy_burden',
    'veb_trigeminy_episodes',
    'veb_trigeminy_burden',
    
    # Supraventricular Ectopic Beats (SVEB)
    'sveb_isolated_count',
    'sveb_isolated_burden',
    'sveb_couplet_episodes',
    'sveb_couplet_burden',
    'sveb_bigeminy_episodes',
    'sveb_bigeminy_burden',
    'sveb_trigeminy_episodes',
    'sveb_trigeminy_burden',
    
    # Ventricular Tachycardia
    'vt_count',
    'longest_vt_start_time',
    'longest_vt_beats_count',
    
    # Supraventricular Tachycardia
    'svt_count',
    'longest_svt_start_time',
    'longest_svt_beats_count',
    
    # Atrial Fibrillation
    'afib_count',
    'afib_burden',
    'longest_afib_start_time',
    'longest_afib_duration',
    'fastest_afib_hr',
    'fastest_afib_start_time',
    
    # Patient triggered events
    'patient_triggered_events_count'
]

def get_tabular_data(metrics, metric_dict_path="../../ft_datasets/ecg_report_dataset/metric_dict.csv"):
    metric_dict = OrderedDict()
    with open(metric_dict_path, mode='r', newline='') as csv_file:
        reader = csv.reader(csv_file)
        for row in reader:
            if len(row) == 2:  # Ensure the row has exactly two columns
                key, value = row
                
                if key == "Metrics" and value == "Description":
                    continue # ignore header
                metric_dict[key] = value
                
    tabular_data = []
    
    for m in metric_dict.keys():  
        desc = metric_dict[m]
        value = "no data" if m not in metrics else metrics[m]
        tabular_data.append(f"{m} | {desc} | {value}")
    
    return tabular_data

            
def get_findings(metrics):
    findings = []

    # Basic monitoring information
    findings.append(f"Monitoring started on {metrics['test_start_time']} and continued for {metrics['test_duration']}.")

    # Predominant rhythm
    if metrics['predominate_rhythm']:
        findings.append(f"The predominant rhythm was {metrics['predominate_rhythm']}.")

    # Heart rate information
    hr_keys = ['overall_max_hr', 'overall_max_hr_time', 'overall_min_hr', 'overall_min_hr_time', 'overall_average_hr']
    if all(metrics.get(key) for key in hr_keys):
        hr_info = (f"The Maximum Heart Rate recorded was {metrics['overall_max_hr']}, {metrics['overall_max_hr_time']}, "
                   f"the Minimum Heart Rate recorded was {metrics['overall_min_hr']}, {metrics['overall_min_hr_time']} "
                   f"and the Average Heart Rate was {metrics['overall_average_hr']}.")
        
        # Pause information
        pause_count = int(metrics.get('pause_count', '0'))
        if pause_count > 0:
            hr_info += f" The study included {pause_count} Pauses."
            if metrics.get('longest_pause_duration') and metrics.get('longest_pause_start_time'):
                hr_info += f" The Longest Pause was {metrics['longest_pause_duration']}, {metrics['longest_pause_start_time']}."
        else:
            hr_info += " There were no pauses detected."
        
        findings.append(hr_info)

    # Ectopic Beats
    sveb_description = describe_beats('sveb', metrics)
    veb_description = describe_beats('veb', metrics)
    
    if veb_description:
        findings.append("Ventricular Ectopic Beats (VEB):")
        findings.extend(f"- {item}" for item in veb_description)

    # Ventricular Tachycardia
    vt_count = int(metrics.get('vt_count', '0'))
    if vt_count > 0:
        vt_info = f"There were {vt_count} occurrences of Ventricular Tachycardia."
        if metrics.get('longest_vt_start_time') and metrics.get('longest_vt_beats_count'):
            vt_info += f" The longest episode was {metrics['longest_vt_beats_count']} beats, {metrics['longest_vt_start_time']}."
        findings.append(vt_info)
    else:
        findings.append("There were no occurrences of Ventricular Tachycardia.")

    if sveb_description:
        findings.append("Supraventricular Ectopic Beats (SVEB):")
        findings.extend(f"- {item}" for item in sveb_description)

    # Supraventricular Tachycardia
    svt_count = int(metrics.get('svt_count', '0'))
    if svt_count > 0:
        svt_info = f"There were {svt_count} occurrences of Supraventricular Tachycardia."
        if metrics.get('longest_svt_start_time') and metrics.get('longest_svt_beats_count'):
            svt_info += f" The longest episode was {metrics['longest_svt_beats_count']} beats, {metrics['longest_svt_start_time']}."
        findings.append(svt_info)
    else:
        findings.append("There were no occurrences of Supraventricular Tachycardia.")

    # Atrial Fibrillation
    afib_count = int(metrics.get('afib_count', '0'))
    if afib_count > 0:
        afib_info = f"The study included an Atrial Fibrillation Burden of {metrics['afib_burden']}."
        if metrics.get('longest_afib_start_time') and metrics.get('longest_afib_duration'):
            afib_info += f" The Longest episode was {metrics['longest_afib_duration']}, {metrics['longest_afib_start_time']}"
            if metrics.get('fastest_afib_hr') and metrics.get('fastest_afib_start_time'):
                afib_info += f" and the Fastest episode was {metrics['fastest_afib_hr']}, {metrics['fastest_afib_start_time']}."
            else:
                afib_info += "."
        findings.append(afib_info)
    else:
        findings.append("There were no occurrences of Atrial Fibrillation.")

    # Patient triggered events
    patient_events = metrics.get('patient_triggered_events_count', '0')
    if patient_events == "0":
        findings.append('Diary event was entered. There were no patient triggered events.')
    else:
        findings.append(f"Diary event was entered. There was {patient_events} patient triggered event{'s' if patient_events != '1' else ''}.")

    return findings

# Helper function (assumed to be defined elsewhere)
def describe_beats(beat_type, metrics):
    description = []
    beat_name = "Supraventricular" if beat_type == "sveb" else "Ventricular"
    
    if metrics[f'{beat_type}_isolated_count'] != "0":
        description.append(f"{metrics[f'{beat_type}_isolated_count']} isolated {beat_name} Ectopic Beats were detected (burden: {metrics[f'{beat_type}_isolated_burden']}).")
    
    for condition in ['couplet', 'bigeminy', 'trigeminy']:
        episodes_key = f'{beat_type}_{condition}_episodes'
        burden_key = f'{beat_type}_{condition}_burden'
        if metrics[episodes_key] != "0":
            description.append(f"{metrics[episodes_key]} {condition} episodes were observed (burden: {metrics[burden_key]}).")
    
    return description

# def get_interpretation(metrics):
#     interpretation = []
#     interpretation.append(f"Rhythm: {metrics['sinus_beat_burden']} (Range {metrics['sinus_min_hr']} - {metrics['sinus_max_hr']}, Avg {metrics['sinus_average_hr']}).")

#     interpretation.append(f"Pause/Block: {metrics['pause_burden']} with {metrics['pause_count']}, No Blocks Present")

#     interpretation.append(f"PVCs: Burden {metrics['veb_isolated_burden']} with {metrics['veb_isolated_count']} singles.")

#     interpretation.append(f"Ventricular: Burden {metrics['veb_isolated_burden']} with {metrics['veb_isolated_count']} singles.")

#     interpretation.append(f"PACs: Burden {metrics['sveb_isolated_burden']} with {metrics['sveb_isolated_count']} singles.")

#     interpretation.append(f"AFib / AFlutter: Burden {metrics['afib_burden']} with {metrics['afib_min_hr_in_bpm']}-{metrics['afib_max_hr_in_bpm']} /min.")
#     interpretation.append("Symptoms: None Present.")

#     print("\n".join(interpretation))
#     return interpretation

# findings = get_findings(metrics)
# print("\n".join(findings))

"""
Findings:

Monitoring started on 09/15/2023 12:54:00 and continued for 22:49:00.
The predominant rhythm was Atrial Rhythm.
The Maximum Heart Rate recorded was 163 bpm, Day 2 / 00:32:27, the Minimum Heart Rate recorded was 58 bpm, Day 2 / 06:10:38 and the Average Heart Rate was 98 bpm. The study included 1 Pauses. The Longest Pause was 2,440ms, Day 1 / 15:28:12.
Ventricular Ectopic Beats (VEB):
- 2603 isolated Ventricular Ectopic Beats were detected (burden: 1.95%).
- 58 couplet episodes were observed (burden: 0.09%).
- 4 bigeminy episodes were observed (burden: <0.01%).
- 2 trigeminy episodes were observed (burden: <0.01%).
There were 32 occurrences of Ventricular Tachycardia. The longest episode was 104 beats beats, Day 2 / 01:25:33.
Supraventricular Ectopic Beats (SVEB):
- 3474 isolated Supraventricular Ectopic Beats were detected (burden: 2.60%).
- 83 couplet episodes were observed (burden: 0.12%).
- 36 bigeminy episodes were observed (burden: 0.09%).
- 52 trigeminy episodes were observed (burden: 0.12%).
There were 6 occurrences of Supraventricular Tachycardia. The longest episode was 5 beats beats, Day 2 / 02:42:42.
The study included an Atrial Fibrillation Burden of 98.9%. The Longest episode was 18:49:30, Day 1 / 16:53:30 and the Fastest episode was 163 bpm, Day 2 / 00:32:27.
Diary event was entered. There were no patient triggered events.
"""


# get_interpretation(metrics)
"""
AF/AFL: AF/AFL was present(98.9%). The Longest episode was 18:49:30, Day 1 / 16:53:30 and the Fastest episode was 163 bpm, Day 2 / 00:32:27.
VEB: 2603 isolated (1.95% burden), 58 couplets, 4 bigeminy, 2 trigeminy episodes.
VT: Total number of VT episodes was 32. The longest episode was 104 beats, Day 2 / 01:25:33.
SVEB: 3474 isolated (2.60% burden), 83 couplets, 36 bigeminy, 52 trigeminy episodes.
SVT: Total number of SVT episodes was 6. The longest episode was 5 beats, Day 2 / 02:42:42.
Pause: Total number of Pauses was 1. The longest episode was 2,440ms, Day 1 / 15:28:12.
Block: No Blocks Present.
Sinus: Sinus rhythm was present(94.7%). The range was 78 - 115 bpm, Avg 96 bpm.
Symptoms: None Present.
"""

# tabular_data = get_tabular_data(metrics)
# print("\t\n".join(tabular_data))
# print("-"*100)
# findings = get_findings(metrics)
# print("\t\n".join(findings))

# print("-"*100)
# get_interpretation(metrics)