import sys
import uuid
from uuid import UUID
import json
import csv

class PassRecord:
    def __init__(self, id, payload, location_in_urv, location_out_urv, timestamp):
        self.id = id
        self.payload = payload
        self.location_in_urv = location_in_urv
        self.location_out_urv = location_out_urv
        self.timestamp = timestamp


def parse_csv_row(row):
    id_field = row[0]
    tail_fields = row[-3:]

    # JSON-поле — всё между первым и последними тремя
    payload_json_str = ",".join(row[1:-3])

    return id_field, payload_json_str, *tail_fields


def main():
    input_file = sys.argv[1]
    output_prefix = sys.argv[2]

    file_counter = 0
    record_counter = 0
    RECORDS_PER_FILE = 100000
    dump_psql = None

    with open(input_file, mode="r") as f:
        csv_reader = csv.reader(f)

        while True:
            if record_counter % RECORDS_PER_FILE == 0:
                if dump_psql:
                    dump_psql.close()

                output_file = f"{output_prefix}_{file_counter:02d}.sql"
                dump_psql = open(output_file, mode="w")

                if file_counter == 0:
                    dump_psql.write("""
                        CREATE TABLE evi.pass_event (
                            id text COLLATE pg_catalog."default" NOT NULL,
                            payload jsonb NOT NULL,
                            location_in_urv boolean NOT NULL,
                            location_out_urv boolean NOT NULL,
                            "timestamp" timestamp with time zone NOT NULL
                        );
                    \n""")

                file_counter += 1

            try:
                row = next(csv_reader)
            except StopIteration:
                break

            if not row:
                continue

            try:
                id_field, payload_str, location_in_urv, location_out_urv, timestamp = parse_csv_row(row)
            except Exception as e:
                print("Ошибка парсинга:", e)
                print("Проблемная строка:", row)
                continue  # или exit(1), как нужно

            payload_str = payload_str.strip()

            if location_in_urv == "t":
                location_in_urv = "true"
            elif location_in_urv == "f":
                location_in_urv = "false"

            if location_out_urv == "t":
                location_out_urv = "true"
            elif location_out_urv == "f":
                location_out_urv = "false"

            record = PassRecord(
                id_field,
                payload_str,
                location_in_urv,
                location_out_urv,
                timestamp
            )

            dump_psql.write(f"""
                INSERT INTO evi.pass_event (id, payload, location_in_urv, location_out_urv, "timestamp")
                VALUES ('{record.id}',
                        '{record.payload.replace("'", "''")}',
                         {record.location_in_urv if record.location_in_urv else ''},
                         {record.location_out_urv if record.location_out_urv else ''},
                        '{record.timestamp}');
            \n""")

            record_counter += 1

        if dump_psql:
            dump_psql.close()

    print(f"Создано файлов pass_event_dump: {file_counter}, всего записей: {record_counter}")

if __name__ == "__main__":
    main()