#!/usr/bin/env python3

import csv
import sqlite3
from argparse import ArgumentParser
from glob import glob

parser = ArgumentParser(description='Counts the number of file and URL groups in the CSV files generated by the Web Cache Exporter.')
parser.add_argument('path', help='The path or search pattern of the CSV files.')
args = parser.parse_args()

connection = sqlite3.connect(':memory:')
connection.execute('CREATE TABLE Csv (FileGroup TEXT NOT NULL, UrlGroup TEXT);')

path_list = glob(args.path)

for i, path in enumerate(path_list, start=1):

	print(f'[{i} of {len(path_list)}] {path}')
	print()

	with open(path, encoding='utf-8', newline='') as file:
		reader = csv.DictReader(file)
		groups = [(row['Custom File Group'], row.get('Custom URL Group')) for row in reader]

	print(f'Total: {len(groups)}')
	print()

	connection.execute('DELETE FROM Csv;')
	connection.executemany('INSERT INTO Csv (FileGroup, UrlGroup) VALUES (?, ?);', groups)
	connection.commit()

	print('File Groups:')

	cursor = connection.execute('SELECT FileGroup, COUNT(*) AS Total FROM Csv GROUP BY FileGroup ORDER BY Total DESC, FileGroup;')
	for row in cursor:
		name, total = row
		print(f'- {name or "N/A"}: {total}')

	print()

	print('URL Groups:')

	cursor = connection.execute('SELECT UrlGroup, COUNT(*) AS Total FROM Csv GROUP BY UrlGroup ORDER BY Total DESC, UrlGroup;')
	for row in cursor:
		name, total = row
		print(f'- {name or "N/A"}: {total}')

	print()

if not path_list:
	print(f'No CSV files found in "{args.path}".')

connection.close()