import sys
import json

def parse_csv_row(row):
    cols = row.split(',')

    if len(cols) < 13:
        raise ValueError(f"Недостаточно столбцов в строке: {row}")

    trigger_id = cols[0].strip()
    name = cols[1].strip()
    active = cols[2].strip()
    _type = cols[3].strip()
    model = cols[4].strip()

    # искать начало JSON и собирать его до тех пор, пока не найдем закрывающую '}'.
    params_start_idx = 5
    if not cols[params_start_idx].strip().startswith('{'):
        raise ValueError(f"Неожиданная структура params в строке: {row}")
    params_parts = []
    bracket_count = 0
    current_idx = params_start_idx

    for i in range(params_start_idx, len(cols)):
        part = cols[i]
        params_parts.append(part)
        for char in part:
            if char == '{':
                bracket_count += 1
            elif char == '}':
                bracket_count -= 1

        if bracket_count == 0 and params_parts[-1].strip().endswith('}'):
            current_idx = i
            break

    if bracket_count != 0:
        raise ValueError(f"Несбалансированные фигурные скобки в params: {row}")

    params = ','.join(params_parts).strip()
    next_idx = current_idx + 1

    if next_idx >= len(cols):
        raise ValueError(f"Недостаточно столбцов для source_camera: {row}")

    source_camera = cols[next_idx].strip()
    next_idx += 1

    if next_idx >= len(cols):
        control_object_state = ""
    else:
        control_object_state = cols[next_idx].strip()
        next_idx += 1

    if next_idx >= len(cols):
        control_object = ""
    else:
        control_object = cols[next_idx].strip()
        next_idx += 1

    if next_idx >= len(cols):
        control_object_trigger = ""
    else:
        control_object_trigger = cols[next_idx].strip()
        next_idx += 1

    if next_idx >= len(cols):
        record_archive_trigger = ""
    else:
        record_archive_trigger = cols[next_idx].strip()
        next_idx += 1

    if next_idx >= len(cols):
        record_camera_gap = ""
    else:
        record_camera_gap = cols[next_idx].strip()
        next_idx += 1

    if next_idx >= len(cols):
        record_camera = ""
    else:
        record_camera = cols[next_idx].strip()

    return trigger_id, name, active, _type, model, params, source_camera, control_object_state, control_object, control_object_trigger, record_archive_trigger, record_camera_gap, record_camera

def extract_direction_from_params(params_json_str, trigger_type):
    if trigger_type == "crossLine":
        try:
            params_dict = json.loads(params_json_str)
            extracted_direction_value = params_dict.get('direction', None)
            return extracted_direction_value
        except json.JSONDecodeError:
            print(f"Ошибка парсинга JSON: {params_json_str}")
            return None
    else:
        return None


class TriggerRecord:
    def __init__(self, trigger_id, name, active, _type, model, params, source_camera, control_object_state,
                control_object, control_object_trigger, record_archive_trigger, record_camera_gap, record_camera):
        self.trigger_id = trigger_id
        self.name = name
        self.active = active
        self._type = _type
        self.model = model
        self.params = params
        self.source_camera = source_camera
        self.control_object_state = control_object_state
        self.control_object = control_object
        self.control_object_trigger = control_object_trigger
        self.record_archive_trigger = record_archive_trigger
        self.record_camera_gap = record_camera_gap
        self.record_camera = record_camera

def main():
    if len(sys.argv) < 3:
        print("Usage: python script.py <input_csv> <output_sql>")
        return 1

    try:
        f = open(sys.argv[1], mode="r", encoding='utf-8')
        dump_file = open(sys.argv[2], mode="w", encoding='utf-8')
    except Exception as e:
        print("Ошибка открытия файлов:", e)
        return 1

    rows = f.read().split("\n")
    f.close()

    dump_file.write("""
    CREATE TABLE evi.camera_analytics_triggers
    (
        trigger_id text COLLATE pg_catalog."default" NOT NULL,
        name text COLLATE pg_catalog."default" NOT NULL,
        active boolean NOT NULL,
        type text COLLATE pg_catalog."default" NOT NULL,
        model text COLLATE pg_catalog."default" NOT NULL,
        with_workers boolean NOT NULL,
        source_camera text COLLATE pg_catalog."default" NOT NULL,
        direction text COLLATE pg_catalog."default",
        action_type text COLLATE pg_catalog."default",
        control_object text COLLATE pg_catalog."default",
        control_object_state text COLLATE pg_catalog."default",
        record_camera text COLLATE pg_catalog."default",
        record_camera_gap bigint,
        time_start text COLLATE pg_catalog."default",
        time_end text COLLATE pg_catalog."default",
        notify boolean,
        save_journal boolean,
        level bigint,
        target_filter_roles jsonb
    );
\n""")

    for row in rows:
        if len(row.strip()) == 0:
            continue

        try:
            trigger_id, name, active, _type, model, params, source_camera, control_object_state, control_object, control_object_trigger, record_archive_trigger, record_camera_gap, record_camera = parse_csv_row(row)
        except Exception as e:
            print("Ошибка парсинга:", e)
            print("Проблемная строка:", row)
            dump_file.close()
            return 1

        record = TriggerRecord(
            trigger_id,
            name,
            active,
            _type,
            model,
            params,
            source_camera,
            control_object_state,
            control_object,
            control_object_trigger,
            record_archive_trigger,
            record_camera_gap,
            record_camera
        )

        if record._type == "recognition":
            with_workers = "true"
        else:
            with_workers = "false"

        direction = extract_direction_from_params(record.params, record._type)

        if record.record_archive_trigger:
            action_type = "recordArchive"
        else:
            action_type = "controlObject"

        record_camera_str = f"'{record.record_camera}'" if record.record_camera else "NULL"
        record_camera_gap_str = f"'{record.record_camera_gap}'" if record.record_camera_gap else "NULL"
        control_object_str = f"'{record.control_object}'" if record.control_object else "NULL"
        control_object_state_str = f"'{record.control_object_state}'" if record.control_object_state else "NULL"

        #time_start, time_end, notify, save_journal, level, target_filter_roles
        dump_file.write(f"""INSERT INTO evi.camera_analytics_triggers (trigger_id, name, active, type, model, with_workers, source_camera, direction,
                    action_type, control_object, control_object_state, record_camera, record_camera_gap)
                        VALUES ('{record.trigger_id}', '{record.name}', '{record.active}', '{record._type}', '{record.model}', '{with_workers}',
                        '{record.source_camera}', {f"'{direction}'" if direction else 'NULL'}, '{action_type}', {control_object_str}, {control_object_state_str},
                        {record_camera_str}, {record_camera_gap_str});\n""")

    dump_file.close()
    return 0

if __name__ == "__main__":
    main()