import sys

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

    # Извлекаем фиксированные поля до grid
    camera_id = cols[0].strip()
    location = cols[1].strip()
    name = cols[2].strip()
    display_label = cols[3].strip()
    analytics = cols[4].strip()
    tcp = cols[5].strip()
    enabled = cols[6].strip()
    sensitivity = cols[7].strip()
    gap_time = cols[8].strip()

    # Собираем grid: начиная с cols[9] до тех пор, пока не найдём grid_x (целое число)
    grid_parts = []
    idx = 9
    while idx < len(cols):
        part = cols[idx].strip()
        grid_parts.append(part)
        idx += 1
        # Проверяем, является ли следующее значение grid_x (целое число)
        if idx < len(cols):
            try:
                int(cols[idx])  # если это число, значит это grid_x
                break
            except ValueError:
                continue

    grid = ','.join(grid_parts)

    # Теперь извлекаем остальные поля
    if idx >= len(cols):
        raise ValueError(f"Недостаточно столбцов после grid: {row}")

    grid_x = cols[idx].strip()
    idx += 1
    if idx >= len(cols):
        raise ValueError(f"Недостаточно столбцов после grid_x: {row}")

    grid_y = cols[idx].strip()
    idx += 1
    if idx >= len(cols):
        raise ValueError(f"Недостаточно столбцов после grid_y: {row}")

    mode = cols[idx].strip()
    idx += 1
    if idx >= len(cols):
        raise ValueError(f"Недостаточно столбцов после mode: {row}")

    archive_days = cols[idx].strip()
    idx += 1
    if idx >= len(cols):
        raise ValueError(f"Недостаточно столбцов после archive_days: {row}")

    pre_buffer = cols[idx].strip()
    idx += 1
    if idx >= len(cols):
        raise ValueError(f"Недостаточно столбцов после pre_buffer: {row}")

    login = cols[idx].strip()
    idx += 1
    if idx >= len(cols):
        raise ValueError(f"Недостаточно столбцов после login: {row}")

    password = cols[idx].strip()
    idx += 1
    if idx >= len(cols):
        raise ValueError(f"Недостаточно столбцов после password: {row}")

    port = cols[idx].strip()
    idx += 1
    if idx >= len(cols):
        raise ValueError(f"Недостаточно столбцов после port: {row}")

    max_object_count = cols[idx].strip()
    idx += 1
    if idx >= len(cols):
        raise ValueError(f"Недостаточно столбцов после max_object_count: {row}")

    active_md = cols[idx].strip()
    idx += 1
    if idx >= len(cols):
        raise ValueError(f"Недостаточно столбцов после active_md: {row}")

    mode_md = cols[idx].strip()

    return (
        camera_id, location, name, display_label, analytics, tcp, enabled,
        sensitivity, gap_time, grid, grid_x, grid_y, mode, archive_days,
        pre_buffer, login, password, port, max_object_count, active_md, mode_md
    )

class CameraRecord:
    def __init__(self, camera_id, location, name, display_label, analytics, tcp, enabled, sensitivity, gap_time, grid, grid_x, grid_y, mode,
    archive_days, pre_buffer, login, password, port, max_object_count, active_md, mode_md):
        self.camera_id = camera_id
        self.location = location
        self.name = name
        self.display_label = display_label
        self.analytics = analytics
        self.tcp = tcp
        self.enabled = enabled
        self.sensitivity = sensitivity
        self.gap_time = gap_time
        self.grid = grid
        self.grid_x = grid_x
        self.grid_y = grid_y
        self.mode = mode
        self.archive_days = archive_days
        self.pre_buffer = pre_buffer
        self.login = login
        self.password = password
        self.port = port
        self.max_object_count = max_object_count
        self.active_md = active_md
        self.mode_md = mode_md

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 IF NOT EXISTS evi.md_profile
    (
        profile_name text COLLATE pg_catalog."default" NOT NULL,
        preconfigured boolean NOT NULL DEFAULT false,
        background_grow_time real NOT NULL,
        background_sabotage_count_max integer NOT NULL,
        background_stat_update_time real NOT NULL,
        background_update_time real NOT NULL,
        calibration_scale_level_max integer NOT NULL,
        classification_shift_min real NOT NULL,
        classification_time_min real NOT NULL,
        debug_annotate_model boolean NOT NULL,
        debug_annotate_moving_regions boolean NOT NULL,
        debug_annotate_tracking_objects boolean NOT NULL,
        debug_draw_level real NOT NULL,
        difference_dx_feature_weight real NOT NULL,
        difference_dy_feature_weight real NOT NULL,
        difference_gray_feature_weight real NOT NULL,
        difference_propagate_forward boolean NOT NULL,
        difference_roi_mask_enable boolean NOT NULL,
        segmentation_create_threshold real NOT NULL,
        segmentation_expand_coefficient real NOT NULL,
        stability_region_area_max real NOT NULL,
        tracking_additional_linking real NOT NULL,
        tracking_averaging_half_range integer NOT NULL,
        tracking_remove_time real NOT NULL,
        tracking_trajectory_max integer NOT NULL,
        CONSTRAINT md_profile_pkey PRIMARY KEY (profile_name)
    )

    TABLESPACE pg_default;

    ALTER TABLE IF EXISTS evi.md_profile
        OWNER to core;
    \n""")

    dump_file.write("""
    CREATE TABLE evi.camera
    (
        camera_id text COLLATE pg_catalog."default" NOT NULL,
        location text COLLATE pg_catalog."default",
        name text COLLATE pg_catalog."default" NOT NULL,
        display_label boolean NOT NULL,
        analytics boolean NOT NULL,
        tcp boolean NOT NULL,
        enabled boolean NOT NULL,
        sensitivity real NOT NULL,
        gap_time integer NOT NULL,
        grid text COLLATE pg_catalog."default" NOT NULL,
        grid_x integer NOT NULL,
        grid_y integer NOT NULL,
        mode integer NOT NULL,
        archive_days integer NOT NULL,
        pre_buffer integer NOT NULL DEFAULT 5,
        login text COLLATE pg_catalog."default",
        password text COLLATE pg_catalog."default",
        port text COLLATE pg_catalog."default",
        max_object_count integer NOT NULL DEFAULT 20,
        active_md boolean NOT NULL DEFAULT false,
        registr boolean NOT NULL DEFAULT true,
        mode_md boolean NOT NULL DEFAULT false,
        md_profile text COLLATE pg_catalog."default",
        size_x real,
        size_y real,
        CONSTRAINT camera_pkey PRIMARY KEY (camera_id),
        CONSTRAINT camera_location_fkey FOREIGN KEY (location)
            REFERENCES evi.location (location_id) MATCH SIMPLE
            ON UPDATE NO ACTION
            ON DELETE SET NULL,
        CONSTRAINT camera_md_profile_fkey FOREIGN KEY (md_profile)
            REFERENCES evi.md_profile (profile_name) MATCH SIMPLE
            ON UPDATE NO ACTION
            ON DELETE SET NULL
    )

    TABLESPACE pg_default;

    ALTER TABLE IF EXISTS evi.camera
        OWNER to core;
    \n""")

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

        try:
            result = parse_camera_row(row)
            (
                camera_id, location, name, display_label, analytics, tcp, enabled,
                sensitivity, gap_time, grid, grid_x, grid_y, mode, archive_days,
                pre_buffer, login, password, port, max_object_count, active_md, mode_md
            ) = result
        except Exception as e:
            print("Ошибка парсинга:", e)
            print("Проблемная строка:", row)
            dump_file.close()
            return 1

        record = CameraRecord(
            camera_id,
            location,
            name,
            display_label,
            analytics,
            tcp,
            enabled,
            sensitivity,
            gap_time,
            grid,
            grid_x,
            grid_y,
            mode,
            archive_days,
            pre_buffer,
            login,
            password,
            port,
            max_object_count,
            active_md,
            mode_md
        )
        registr = "true"
        md_profile = "NULL"
        size_x = "NULL"
        size_y = "NULL"

        dump_file.write(f"""INSERT INTO evi.camera (camera_id, location, name, display_label, analytics, tcp, enabled, sensitivity, gap_time, grid, grid_x,
        grid_y, mode, archive_days, pre_buffer, login, password, port, max_object_count, active_md, registr, mode_md, md_profile, size_x, size_y)
                        VALUES ('{record.camera_id}', '{record.location}', '{record.name}', '{record.display_label}', '{record.analytics}', '{record.tcp}',
                        '{record.enabled}', '{record.sensitivity}', '{record.gap_time}', '{record.grid}', '{record.grid_x}', '{record.grid_y}',
                        '{record.mode}', '{record.archive_days}', '{record.pre_buffer}', '{record.login}', '{record.password}', '{record.port}',
                        '{record.max_object_count}', '{record.active_md}', '{registr}', '{record.mode_md}', {md_profile}, {size_x}, {size_y});\n""")
    dump_file.close()
    return 0

if __name__ == "__main__":
    main()