import sys

def parse_divisions_row(row):
    idx = row.find(',')
    if idx == -1:
        raise ValueError(f"Неверный формат строки: {row}")

    division_id = row[:idx].strip()
    name = row[idx + 1:].strip()

    return division_id, name

class DivisionsRecord:
    def __init__(self, division_id, name):
        self.division_id = division_id
        self.name = name

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.division
(
    division_id text COLLATE pg_catalog."default" NOT NULL,
    name text COLLATE pg_catalog."default" NOT NULL,
    CONSTRAINT division_pkey PRIMARY KEY (division_id),
    CONSTRAINT division_unique_name_cnt UNIQUE (name)
);
\n""")

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

        try:
            division_id, name = parse_divisions_row(row)
        except Exception as e:
            print("Ошибка парсинга:", e)
            print("Проблемная строка:", row)
            dump_file.close()
            return 1

        record = DivisionsRecord(division_id, name)

        # Экранируем апострофы в name
        safe_name = record.name.replace("'", "''")

        dump_file.write(f"""INSERT INTO evi.division (division_id, name)
                    VALUES ('{record.division_id}', '{safe_name}');\n""")

    dump_file.close()
    return 0

if __name__ == "__main__":
    main()