#!/usr/bin/env python3
import json
import sqlite3
import sys
from pathlib import Path

TABLES = [
    'AspNetUsers',
    'AspNetRoles',
    'AspNetUserRoles',
    'Companies',
    'JobApplications',
    'Correspondences',
    'Attachments',
    'JobEvents',
    'GmailConnections',
    'UserRuleSettings',
]


def export_db(sqlite_path: str, output_path: str) -> None:
    conn = sqlite3.connect(sqlite_path)
    conn.row_factory = sqlite3.Row
    payload = {}
    for table in TABLES:
        try:
            rows = conn.execute(f'SELECT * FROM {table}').fetchall()
            payload[table] = [dict(row) for row in rows]
        except sqlite3.Error:
            payload[table] = []
    Path(output_path).write_text(json.dumps(payload, default=str, indent=2), encoding='utf-8')
    conn.close()


if __name__ == '__main__':
    if len(sys.argv) != 3:
        print('Usage: sqlite_export.py <sqlite-db-path> <output-json>')
        raise SystemExit(1)
    export_db(sys.argv[1], sys.argv[2])
