<?php
declare(strict_types=1);
require_once __DIR__ . '/_util.php';

$worldPath = data_path('world.json');
$world = read_json($worldPath);
if (!$world) json_response(["error" => "Missing or invalid data/world.json"], 500);

$weekday = get_weekday_index();
$champId = $world['activeChampionByWeekday'][(string)$weekday] ?? 'mon';

$champPath = data_path("champions/$champId.json");
$champ = read_json($champPath);
if (!$champ) json_response(["error" => "Missing champion file: data/champions/$champId.json"], 500);

// Quests
$dailies = read_json(data_path('quests/dailies.json')) ?? [];
$goals = read_json(data_path('quests/goals.json')) ?? [];
$randomPool = read_json(data_path('quests/random_pool.json')) ?? [];

// Inventory (shared) — NOTE: stash.json (not groceries.json)
$inventory = [
  "supplements" => read_json(data_path('inventory/supplements.json')) ?? ["category"=>"supplements","grid"=>["cols"=>12,"rows"=>5],"items"=>[]],
  "stash"       => read_json(data_path('inventory/stash.json')) ?? ["category"=>"stash","grid"=>["cols"=>12,"rows"=>5],"items"=>[]],
  "wishlist"    => read_json(data_path('inventory/wishlist.json')) ?? ["category"=>"wishlist","grid"=>["cols"=>12,"rows"=>5],"items"=>[]],
];

// Ensure today random picks exist (persisted)
$date = today_ymd();
if (!isset($world['dailyPicks']['byDate'][$date][$champId])) {
  $picksPerDay = (int)($world['rules']['dailyRandom']['picksPerDay'] ?? 3);

  $poolIds = [];
  foreach ($randomPool as $q) {
    if (isset($q['id'])) $poolIds[] = $q['id'];
  }

  // Deterministic “random” based on champ+date (won’t reroll on refresh)
  $seed = crc32($champId . '|' . $date);
  mt_srand($seed);

  $unique = [];
  $max = count($poolIds);
  while (count($unique) < min($picksPerDay, $max) && $max > 0) {
    $idx = mt_rand(0, $max - 1);
    $unique[$poolIds[$idx]] = true;
  }

  $world['dailyPicks']['byDate'][$date][$champId] = array_values(array_keys($unique));
  $world['lastSavedAt'] = iso_now();
  write_json_atomic($worldPath, $world);
}

$todayRandomIds = $world['dailyPicks']['byDate'][$date][$champId];

// Ensure tag ledger exists for combos/milestones
if (!isset($world['dailyTagLedger']['byDate'][$date][$champId])) {
  $world['dailyTagLedger']['byDate'][$date][$champId] = ["tags" => [], "awardedCombos" => [], "awardedMilestones" => []];
  $world['lastSavedAt'] = iso_now();
  write_json_atomic($worldPath, $world);
}

json_response([
  "date" => $date,
  "weekdayIndex" => $weekday,
  "activeChampionId" => $champId,
  "world" => $world,
  "champion" => $champ,
  "quests" => [
    "dailies" => $dailies,
    "goals" => $goals,
    "randomPool" => $randomPool,
    "todayRandomIds" => $todayRandomIds
  ],
  "inventory" => $inventory
]);