"""
scripts/logs.py
Script used for logging Prestonet Chrome Extension
Author: Vojtech Pokorny, vojtech.pokorny@prestonet.cz
Date (last edit): 6.2.2025
Note:
"""

import json
import re

def get_button_logs(file_path, button_name):
	filtered_logs = []

	# Regex pattern to extract the timestamp and JSON part of the log
	log_pattern = re.compile(r'^(\d{4}-\d{2}-\d{2} \d{2}:\d{2}:\d{2},\d+) - (.*)$')

	with open(file_path, 'r', encoding='utf-8') as file:
		for line in file:
			match = log_pattern.search(line)
			if match:
				timestamp = match.group(1)  # Extract timestamp
				try:
					log_data = json.loads(match.group(2))  # Parse JSON part of the log
					# Check if button matches and add timestamp to the log
					if log_data.get("message", {}).get("button") == button_name:
						filtered_logs.append({"timestamp": timestamp, "log": log_data})
				except json.JSONDecodeError:
					continue  # Skip lines that aren't valid JSON

	return filtered_logs

async def add_log_to_db(
    db_pool,
    user: str,
    source: str,
    button: str,
    webhook_url: str,
    run_id: str,
    status: str
):
    async with db_pool.acquire() as conn:
        await conn.execute("""
            INSERT INTO logs ("user", "source", "button", "webhook_url", "run_id", "status")
            VALUES ($1, $2, $3, $4, $5, $6)
        """, user, source, button, webhook_url, run_id, status)


