import csv
import os
import logging

logger = logging.getLogger(__name__)

PROACTIVE_CSV, PROACTIVE_ENV_CSV = "proactive.csv", "proactive_env.csv"
PROACTIVE_SQL = """SELECT
  id, timestamp, ip, ip_int, ip_version, ip_country_id, description, action,
  host, path, url, count, uid, gid, rule_id, rule_name
FROM proactive ORDER BY timestamp DESC LIMIT ?"""
PROACTIVE_ENV_SQL = """
SELECT proactive_env.event_id, proactive_env.name, proactive_env.value
FROM proactive_env INNER JOIN ({}) pa ON proactive_env.event_id=pa.id
""".format(
    PROACTIVE_SQL
)
EXPORT_DIR = "/var/lib/imunify360-php-daemon/export"


def export(database, target_dir, events_num):
    for filename, query in [
        (PROACTIVE_CSV, PROACTIVE_SQL),
        (PROACTIVE_ENV_CSV, PROACTIVE_ENV_SQL),
    ]:
        cur = database.execute_sql(query, (events_num,))
        with open(
            os.path.join(target_dir, filename),
            "w",
            newline="",
            encoding="utf-8",
        ) as csvfile:
            csv_writer = csv.writer(csvfile)
            csv_writer.writerows(cur)


def migrate(migrator, database, fake=False, **kwargs):
    if fake:
        return
    try:
        os.makedirs(EXPORT_DIR, exist_ok=True)
        export(database, EXPORT_DIR, 1000)
    except Exception:
        # not critical
        logger.exception("Failed to export proactive defence data")


def rollback(migrator, database, fake=False, **kwargs):
    pass
