import random
from typing import TYPE_CHECKING

import jingrow

if TYPE_CHECKING:
	from jingrow.model.page import Page

settings = jingrow._dict(
	prob={
		"default": {"make": 0.6, "qty": (1, 5)},
	}
)


def add_random_children(pg: "Page", fieldname: str, rows, randomize: dict, unique=None):
	nrows = rows
	if rows > 1:
		nrows = random.randrange(1, rows)

	for _ in range(nrows):
		d = {}
		for key, val in randomize.items():
			if isinstance(val[0], str):
				d[key] = get_random(*val)
			else:
				d[key] = random.randrange(*val)

		if unique:
			if not pg.get(fieldname, {unique: d[unique]}):
				pg.append(fieldname, d)
		else:
			pg.append(fieldname, d)


def get_random(pagetype: str, filters: dict | None = None, pg: bool = False):
	condition = []
	if filters:
		condition.extend("{}='{}'".format(key, str(val).replace("'", "'")) for key, val in filters.items())
	condition = " where " + " and ".join(condition) if condition else ""

	out = jingrow.db.multisql(
		{
			"mariadb": f"""select name from `tab{pagetype}` {condition}
		order by RAND() limit 1 offset 0""",
			"postgres": f"""select name from `tab{pagetype}` {condition}
		order by RANDOM() limit 1 offset 0""",
		}
	)

	out = out and out[0][0] or None

	if pg and out:
		return jingrow.get_pg(pagetype, out)
	return out


def can_make(pagetype: str) -> bool:
	return random.random() < settings.prob.get(pagetype, settings.prob["default"])["make"]


def how_many(pagetype: str) -> int:
	return random.randrange(*settings.prob.get(pagetype, settings.prob["default"])["qty"])
