from dotenv import load_dotenv
load_dotenv()

import sys
import os
import re
import json

import psycopg2

from meme_classifier.images import process_image

path = sys.argv[1]
data = json.load(open(os.path.join(path, 'result.json'), 'r'))
chat_id = data['id']
conn = psycopg2.connect(os.getenv('POSTGRES_CREDENTIALS'))

for m in data['messages']:
    if 'photo' in m:
        template, text = process_image(open(os.path.join(path, m['photo']), 'rb'))
        message_id = m['id']
        print(f'processing message {message_id}')

        cur = conn.cursor()
        cur.execute("INSERT INTO meme (template, text, chat_id, message_id) VALUES (%s, %s, %s, %s)", (template, text, chat_id, message_id))
        conn.commit()

[((2, 0, 2, 13), 'dotenv.load_dotenv', 'load_dotenv', ({}, {}), '()', False, 'from dotenv import load_dotenv\n'), ((16, 24, 16, 57), 'os.getenv', 'os.getenv', ({(16, 34, 16, 56): '"""POSTGRES_CREDENTIALS"""'}, {}), "('POSTGRES_CREDENTIALS')", False, 'import os\n'), ((14, 22, 14, 55), 'os.path.join', 'os.path.join', ({(14, 35, 14, 39): 'path', (14, 41, 14, 54): '"""result.json"""'}, {}), "(path, 'result.json')", False, 'import os\n'), ((20, 44, 20, 74), 'os.path.join', 'os.path.join', ({(20, 57, 20, 61): 'path', (20, 63, 20, 73): "m['photo']"}, {}), "(path, m['photo'])", False, 'import os\n')]