import sys
import csv

class PhotoRecord:
    def __init__(self, photo_id, data, data_low, _type, analytics):
        self.photo_id = photo_id
        self.data = data
        self.data_low = data_low
        self._type = _type
        self.analytics = analytics

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

    file_counter = 0
    record_counter = 0
    RECORDS_PER_FILE = 100
    dump_psql = None
    csv.field_size_limit(sys.maxsize)

    with open(input_file, mode="r", encoding='utf-8') 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", encoding='utf-8')

                if file_counter == 0:
                    dump_psql.write("""
                    CREATE TABLE evi.photo
                    (
                        photo_id text COLLATE pg_catalog."default" NOT NULL,
                        data bytea NOT NULL,
                        data_low bytea,
                        type text COLLATE pg_catalog."default" NOT NULL,
                        analytics boolean NOT NULL,
                        comment text COLLATE pg_catalog."default",
                        CONSTRAINT photo_pkey PRIMARY KEY (photo_id)
                    );
                    \n""")

                file_counter += 1

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

            if not row:
                print("not row")
                continue

            try:
                record = PhotoRecord(row[0], row[1], row[2], row[3], row[4])
            except IndexError:
                print("Ошибка: недостаточно столбцов в строке:", row)
                continue
            except Exception as e:
                print("Ошибка парсинга:", e)
                print("Проблемная строка:", row)
                continue

            comment = "NULL"

            dump_psql.write(f"""INSERT INTO evi.photo (photo_id, data, data_low, type, analytics, comment)
                            VALUES ('{record.photo_id}', '{record.data}', '{record.data_low}', '{record._type}', '{record.analytics}', {comment});\n""")

            record_counter += 1

        if dump_psql:
            dump_psql.close()

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

if __name__ == "__main__":
    main()