"""Import CloudTrail logs with the installed DuckLocal CLI, one file at a time."""

import argparse
import json
from pathlib import Path
import subprocess


def main():
    parser = argparse.ArgumentParser(description=__doc__)
    parser.add_argument('logs', type=Path, help='Directory containing extracted .json.gz files')
    parser.add_argument('database', type=Path, help='New database path; must not already exist')
    args = parser.parse_args()
    files = sorted(args.logs.resolve().rglob('*.json.gz'))
    if not files:
        parser.error('No .json.gz files found; check the extraction directory and filenames')
    database = args.database.resolve()
    if database.exists():
        parser.error('Database already exists; choose a new path to avoid duplicate imports')
    if not database.parent.is_dir():
        parser.error('Database parent directory does not exist')
    template = Path(__file__).with_name('cloudtrail-import.sql').read_text(encoding='utf-8')
    placeholder = 'C:/data/flaws/flaws_cloudtrail_logs/flaws_cloudtrail00.json.gz'
    if placeholder not in template:
        parser.error('Use the unedited cloudtrail-import.sql beside this script')
    total = 0
    for index, file in enumerate(files):
        sql = template.replace(placeholder, file.as_posix().replace("'", "''"))
        if index:
            sql = sql.replace('CREATE TABLE cloudtrail_events AS', 'INSERT INTO cloudtrail_events')
        print(f'[{index + 1}/{len(files)}] {file.name}', flush=True)
        result = subprocess.run(
            ['ducklocal', 'query', '--database', str(database), '--read-write', '--sql', sql],
            capture_output=True, text=True, encoding='utf-8',
        )
        if result.returncode:
            raise SystemExit(
                f'Import stopped at {file}. Earlier batches remain in {database}.\n'
                'Choose a new database path for a fresh run.\n' + result.stderr + result.stdout
            )
        output = json.loads(result.stdout)
        if output['truncated']:
            raise SystemExit('Unexpected truncated import result; inspect the database')
        count = output['rows'][0][0]
        total += count
        print(f'  Imported {count:,} events; total {total:,}', flush=True)
    print(f'Database: {database}')


if __name__ == '__main__':
    main()
