#!/usr/bin/env bash
# ============================================================================
# TC-22 — Compendiums
# Usage: ./tc-22-compendiums.sh [--navigate]
# ============================================================================
set -uo pipefail
source "$(dirname "$0")/tc-header.sh"

echo ""
echo "╔══════════════════════════════════════════════════════════════╗"
echo "║   TC-22 — Compendiums                                       ║"
echo "╚══════════════════════════════════════════════════════════════╝"
echo ""

tc_ensure_ready

# ============================================================================
echo "--- TC-22-001: Packs chargés ---"
# ============================================================================
R=$(jse_get_async "
	try {
		const packs = game.packs.filter(p => p.metadata?.system === 'foundryvtt-reve-de-dragon');
		return { count: packs.length, names: packs.map(p => p.metadata?.name).join(',') };
	} catch(e) { return {error: e.message}; }
")
COUNT=$(eval_ok "$R" count)
ERR=$(eval_ok "$R" error)
assert_gt "TC-22-001: ≥10 packs chargés ($COUNT)" "$COUNT" 9

# ============================================================================
echo "--- TC-22-002: Compendium Compétences ---"
# ============================================================================
R=$(jse_get_async "
	try {
		const packs = game.packs.filter(p => p.metadata?.system === 'foundryvtt-reve-de-dragon');
		const compPack = packs.find(p => p.metadata?.name?.includes('competence') || p.metadata?.label?.toLowerCase().includes('comp'));
		if (!compPack) return {error: 'no competence pack', names: packs.map(p=>p.metadata.name).join(',')};
		const docs = await compPack.getDocuments();
		return { count: docs.length, valid: docs.length > 10 };
	} catch(e) { return {error: e.message}; }
")
CCOUNT=$(eval_ok "$R" count)
CVALID=$(eval_ok "$R" valid)
ERR=$(eval_ok "$R" error)
[ "$CVALID" = "True" ] && pass "TC-22-002: compétences pack = $CCOUNT items" || fail "TC-22-002: KO ($ERR)"

# ============================================================================
echo "--- TC-22-003: Compendium Sorts ---"
# ============================================================================
R=$(jse_get_async "
	try {
		const packs = game.packs.filter(p => p.metadata?.system === 'foundryvtt-reve-de-dragon');
		const sortPack = packs.find(p => p.metadata?.name?.includes('sort') || p.metadata?.label?.toLowerCase().includes('sort'));
		if (!sortPack) return {error: 'no sort pack'};
		const docs = await sortPack.getDocuments();
		return { count: docs.length, valid: docs.length > 20 };
	} catch(e) { return {error: e.message}; }
")
SCOUNT=$(eval_ok "$R" count)
SVALID=$(eval_ok "$R" valid)
ERR=$(eval_ok "$R" error)
[ "$SVALID" = "True" ] && pass "TC-22-003: sorts pack = $SCOUNT items" || fail "TC-22-003: KO ($ERR)"

# ============================================================================
echo "--- TC-22-004: Compendium Équipement ---"
# ============================================================================
R=$(jse_get_async "
	try {
		const packs = game.packs.filter(p => p.metadata?.system === 'foundryvtt-reve-de-dragon');
		const eqPack = packs.find(p => p.metadata?.name?.includes('equipement') || p.metadata?.name?.includes('arme') || p.metadata?.label?.toLowerCase().includes('quip'));
		if (!eqPack) return {error: 'no equipement pack'};
		const docs = await eqPack.getDocuments();
		return { count: docs.length, valid: docs.length > 5 };
	} catch(e) { return {error: e.message}; }
")
ECOUNT=$(eval_ok "$R" count)
EVALID=$(eval_ok "$R" valid)
ERR=$(eval_ok "$R" error)
[ "$EVALID" = "True" ] && pass "TC-22-004: équipement pack = $ECOUNT items" || fail "TC-22-004: KO ($ERR)"

# ============================================================================
echo "--- TC-22-006: Drag compendium → acteur ---"
# ============================================================================
R=$(jse_get_async "
	try {
		const packs = game.packs.filter(p => p.metadata?.system === 'foundryvtt-reve-de-dragon');
		// Find an item pack
		const itemPack = packs.find(p => p.documentName === 'Item');
		if (!itemPack) return {error: 'no item pack'};
		const docs = await itemPack.getDocuments();
		if (docs.length === 0) return {error: 'empty pack'};
		// Create a test actor
		const [actor] = await Actor.createDocuments([{type:'personnage', name:'TC-22 Test'}]);
		// Get first item from pack
		const item = docs[0];
		// Clone it to actor
		const [created] = await actor.createEmbeddedDocuments('Item', [item.toObject()]);
		const has = actor.items.has(created.id);
		await actor.delete();
		return { dragOk: has, itemName: item.name };
	} catch(e) { return {error: e.message}; }
")
DRAGOK=$(eval_ok "$R" dragOk)
ERR=$(eval_ok "$R" error)
[ "$DRAGOK" = "True" ] && pass "TC-22-006: drag compendium → acteur" || fail "TC-22-006: KO ($ERR)"

# ============================================================================
echo ""
echo "--- Console errors ---"
ERRS=$(tc_console_errors)
[ "$ERRS" -le 5 ] 2>/dev/null && pass "Console errors ≤5 ($ERRS)" || fail "Console errors: $ERRS"

tc_summary