using System.Text.Json;
using Meezi.Infrastructure.Data;

static string FindRepoRoot()
{
    var dir = new DirectoryInfo(AppContext.BaseDirectory);
    while (dir is not null)
    {
        if (File.Exists(Path.Combine(dir.FullName, "MEEZI_PRD.md"))
            || Directory.Exists(Path.Combine(dir.FullName, "data")))
            return dir.FullName;
        dir = dir.Parent;
    }

    return Path.GetFullPath(Path.Combine(AppContext.BaseDirectory, "..", "..", "..", ".."));
}

var repoRoot = FindRepoRoot();
var manifestPath = Path.Combine(repoRoot, "data", "menu-image-manifest.json");
var demoMenuPath = Path.Combine(repoRoot, "data", "demo-menu-food101.json");

var items = new Dictionary<string, object>(StringComparer.Ordinal);
foreach (var item in DemoMenuCatalog.Items)
{
    items[item.Id] = new
    {
        food101Class = item.Food101Class,
        imageUrl = Food101ImageFallbacks.Resolve(
            item.Food101Class,
            MenuItemImageDefaults.InferKind(item.CategoryId)),
        nameEn = item.NameEn,
        categoryId = item.CategoryId
    };
}

var manifest = new
{
    version = 2,
    source = "Food-101 class mapping (Unsplash fallbacks until Kaggle JPEG import)",
    defaults = new
    {
        drink = MenuImageManifest.GetDefaultDrinkImageUrl(),
        food = MenuImageManifest.GetDefaultFoodImageUrl()
    },
    items
};

var options = new JsonSerializerOptions { WriteIndented = true };
await File.WriteAllTextAsync(manifestPath, JsonSerializer.Serialize(manifest, options) + Environment.NewLine);

var demoExport = new
{
    version = 1,
    cafeId = "cafe_demo_001",
    categories = DemoMenuCatalog.Categories,
    items = DemoMenuCatalog.Items.Select(i => new
    {
        i.Id,
        i.CategoryId,
        i.Name,
        i.NameEn,
        i.NameAr,
        i.Description,
        priceToman = i.PriceToman,
        i.DiscountPercent,
        i.Food101Class,
        imageUrl = DemoMenuCatalog.ResolveItemImageUrl(i)
    })
};
await File.WriteAllTextAsync(demoMenuPath, JsonSerializer.Serialize(demoExport, options) + Environment.NewLine);

Console.WriteLine($"Wrote {items.Count} items → {manifestPath}");
Console.WriteLine($"Wrote demo menu export → {demoMenuPath}");
