import sys
import csv
import json
import re

class CriticalEventRecord:
    def __init__(self, id, payload, timestamp, confirmed, user_login, user_id):
        self.id = id
        self.payload = payload
        self.timestamp = timestamp
        self.confirmed = confirmed
        self.user_login = user_login
        self.user_id = user_id

dump_file = open(sys.argv[2], mode="w")
dump_file.write("""
CREATE TABLE evi.critical_event (
    id text NOT NULL,
    payload jsonb NOT NULL,
    "timestamp" timestamp with time zone NOT NULL,
    confirmed boolean,
    user_login text,
    user_id text,
    CONSTRAINT critical_event_pkey PRIMARY KEY (id),
    CONSTRAINT critical_event_unique_event_cnt UNIQUE ("timestamp", payload)
);
\n""")

with open(sys.argv[1], 'r', encoding='utf-8') as f:
    for line in f:
        line = line.strip()
        if not line:
            break

        json_match = re.search(r'(\{.*\})', line)
        if not json_match:
            break

        json_str = json_match.group(1)
        payload_j = json.loads(json_str)

        before_json = line[:json_match.start()].rstrip(',')
        parts_before = before_json.split(',')

        after_json = line[json_match.end():].lstrip(',')
        parts_after = after_json.split(',')

        if 'di' in json_str:
            for entity in payload_j["entity"]:
                if entity["type"] == "di":
                    entity["nameDi"] = ''

        elif "prevDi" in json_str:
            for entity in payload_j["entity"]:
                if entity["type"] == "prevDi":
                    entity["nameDi"] = ''

        record = CriticalEventRecord(parts_before[0], payload_j, parts_after[0], parts_after[1], parts_after[2], parts_after[3])

        confirmed = f"False" if record.confirmed == "f" else "True"
        dump_file.write(f"""INSERT INTO evi.critical_event (id, payload, timestamp, confirmed, user_login, user_id)
                        VALUES ('{record.id}', '{json.dumps(record.payload)}', '{record.timestamp}', {confirmed}, '{record.user_login}', '{record.user_id}');\n""")
