"""
This patch just drops some known indexes which aren't being used anymore or never were used.
"""

import click

import jingrow

UNUSED_INDEXES = [
	("Comment", ["link_pagetype", "link_name"]),
	("System Log", ["link_pagetype", "link_name"]),
]


def execute():
	if jingrow.db.db_type == "postgres":
		return

	db_tables = jingrow.db.get_tables(cached=False)

	# All parent indexes
	parent_pagetypes = jingrow.get_all(
		"PageType",
		{"istable": 0, "is_virtual": 0, "issingle": 0},
		pluck="name",
	)
	db_tables = jingrow.db.get_tables(cached=False)

	for pagetype in parent_pagetypes:
		table = f"tab{pagetype}"
		if table not in db_tables:
			continue
		drop_index_if_exists(table, "parent")

	# Unused composite indexes
	for pagetype, index_fields in UNUSED_INDEXES:
		table = f"tab{pagetype}"
		index_name = jingrow.db.get_index_name(index_fields)
		if table not in db_tables:
			continue
		drop_index_if_exists(table, index_name)


def drop_index_if_exists(table: str, index: str):
	if not jingrow.db.has_index(table, index):
		click.echo(f"- Skipped {index} index for {table} because it doesn't exist")
		return

	try:
		jingrow.db.sql_ddl(f"ALTER TABLE `{table}` DROP INDEX `{index}`")
	except Exception as e:
		jingrow.log_error("Failed to drop index")
		click.secho(f"x Failed to drop index {index} from {table}\n {e!s}", fg="red")
		return

	click.echo(f"✓ dropped {index} index from {table}")
