import RegionData from "../../models/falukant/data/region.js";
import RegionType from "../../models/falukant/type/region.js";
import Relationship from "../../models/falukant/type/relationship.js";
import Mood from "../../models/falukant/type/mood.js";
import CharacterTrait from "../../models/falukant/type/character_trait.js";
import PromotionalGift from "../../models/falukant/type/promotional_gift.js";
import PromotionalGiftCharacterTrait from "../../models/falukant/predefine/promotional_gift_character_trait.js";
import PromotionalGiftMood from "../../models/falukant/predefine/promotional_gift_mood.js";
import { sequelize } from '../sequelize.js';
import HouseType from '../../models/falukant/type/house.js';
import TitleOfNobility from "../../models/falukant/type/title_of_nobility.js";
import PartyType from "../../models/falukant/type/party.js";
import MusicType from "../../models/falukant/type/music.js";
import BanquetteType from "../../models/falukant/type/banquette.js";
import ReputationActionType from "../../models/falukant/type/reputation_action.js";
import VehicleType from "../../models/falukant/type/vehicle.js";
import LearnRecipient from "../../models/falukant/type/learn_recipient.js";
import PoliticalOfficeType from "../../models/falukant/type/political_office_type.js";
import PoliticalOfficeBenefitType from "../../models/falukant/type/political_office_benefit_type.js";
import PoliticalOfficePrerequisite from "../../models/falukant/predefine/political_office_prerequisite.js";
import UndergroundType from "../../models/falukant/type/underground.js";
import WeatherType from "../../models/falukant/type/weather.js";
import Weather from "../../models/falukant/data/weather.js";
import ProductWeatherEffect from "../../models/falukant/type/product_weather_effect.js";
import ProductType from "../../models/falukant/type/product.js";

// Debug-Flag: Nur wenn DEBUG_FALUKANT=1 gesetzt ist, werden ausführliche Logs ausgegeben.
const falukantDebug = process.env.DEBUG_FALUKANT === '1';

export const initializeFalukantTypes = async () => {
    await initializeFalukantTypeRegions();
    await initializeFalukantRelationships();
    await initializeFalukantMoods();
    await initializeFalukantCharacterTraits();
    await initializeFalukantPromotionalGifts();
    await initializePromotionalGiftMoodLinks();
    
    // Adelstitel VOR Haustypen initialisieren
    await initializeFalukantTitlesOfNobility();
    
    await initializeFalukantHouseTypes();
    await initializeFalukantPartyTypes();
    await initializeFalukantMusicTypes();
    await initializeFalukantBanquetteTypes();
    await initializeFalukantReputationActions();
    await initializeLearnerTypes();
    await initializePoliticalOfficeBenefitTypes();
    await initializePoliticalOfficeTypes();
    await initializePoliticalOfficePrerequisites();
    await initializeUndergroundTypes();
    await initializeVehicleTypes();
    await initializeFalukantWeatherTypes();
    await initializeFalukantWeathers();
    await initializeFalukantProductWeatherEffects();
};

const reputationActions = [
    // Günstig / häufig: schnelle Abnutzung
    { tr: "soup_kitchen", cost: 500, baseGain: 2, decayFactor: 0.85, minGain: 0, decayWindowDays: 7 },
    // Mittel: gesellschaftlich anerkannt
    { tr: "library_donation", cost: 5000, baseGain: 4, decayFactor: 0.88, minGain: 0, decayWindowDays: 7 },
    { tr: "scholarships", cost: 10000, baseGain: 5, decayFactor: 0.87, minGain: 0, decayWindowDays: 7 },
    { tr: "church_hospice", cost: 12000, baseGain: 5, decayFactor: 0.87, minGain: 0, decayWindowDays: 7 },
    { tr: "school_funding", cost: 15000, baseGain: 6, decayFactor: 0.88, minGain: 0, decayWindowDays: 7 },
    // Großprojekte: teurer, langsamerer Rufverfall
    { tr: "orphanage_build", cost: 20000, baseGain: 7, decayFactor: 0.90, minGain: 0, decayWindowDays: 7 },
    { tr: "bridge_build", cost: 25000, baseGain: 7, decayFactor: 0.90, minGain: 0, decayWindowDays: 7 },
    { tr: "hospital_donation", cost: 30000, baseGain: 8, decayFactor: 0.90, minGain: 0, decayWindowDays: 7 },
    { tr: "patronage", cost: 40000, baseGain: 9, decayFactor: 0.91, minGain: 0, decayWindowDays: 7 },
    { tr: "statue_build", cost: 50000, baseGain: 10, decayFactor: 0.92, minGain: 0, decayWindowDays: 7 },
    { tr: "well_build", cost: 8000, baseGain: 4, decayFactor: 0.87, minGain: 0, decayWindowDays: 7 },
];

async function initializeFalukantReputationActions() {
    // robustes Upsert ohne FK/Constraints-Ärger:
    // - finde existierende nach tr
    // - update bei Änderungen
    // - create wenn fehlt
    const existing = await ReputationActionType.findAll({ attributes: ['id', 'tr', 'cost', 'baseGain', 'decayFactor', 'minGain'] });
    const existingByTr = new Map(existing.map(e => [e.tr, e]));

    for (const a of reputationActions) {
        const found = existingByTr.get(a.tr);
        if (!found) {
            await ReputationActionType.create(a);
            continue;
        }
        const needsUpdate =
            Number(found.cost) !== Number(a.cost) ||
            Number(found.baseGain) !== Number(a.baseGain) ||
            Number(found.decayFactor) !== Number(a.decayFactor) ||
            Number(found.minGain) !== Number(a.minGain) ||
            Number(found.decayWindowDays || 7) !== Number(a.decayWindowDays || 7);
        if (needsUpdate) {
            await found.update({
                cost: a.cost,
                baseGain: a.baseGain,
                decayFactor: a.decayFactor,
                minGain: a.minGain,
                decayWindowDays: a.decayWindowDays ?? 7,
            });
        }
    }
}

const regionTypes = [];
const regionTypeTrs = [
    "country",
    "duchy",
    "markgravate",
    "shire",
    "county",
    "city"
];

const regions = [
    { labelTr: "falukant", regionType: "country", parentTr: null },
    { labelTr: "Hessen", regionType: "duchy", parentTr: "falukant" },
    { labelTr: "Groß-Benbach", regionType: "markgravate", parentTr: "Hessen" },
    { labelTr: "Siebenbachen", regionType: "shire", parentTr: "Groß-Benbach" },
    { labelTr: "Bad Homburg", regionType: "county", parentTr: "Siebenbachen" },
    { labelTr: "Maintal", regionType: "county", parentTr: "Siebenbachen" },
    { labelTr: "Frankfurt", regionType: "city", parentTr: "Bad Homburg", map: { x: 187, y: 117, w: 10, h: 11 } },
    { labelTr: "Oberursel", regionType: "city", parentTr: "Bad Homburg", map: { x: 168, y: 121, w: 10, h: 11 } },
    { labelTr: "Offenbach", regionType: "city", parentTr: "Bad Homburg", map: { x: 171, y: 142, w: 10, h: 11 } },
    { labelTr: "Königstein", regionType: "city", parentTr: "Maintal", map: { x: 207, y: 124, w: 24, h: 18 } },
];

const relationships = [
    { tr: "wooing" },
    { tr: "engaged" },
    { tr: "married" },
    { tr: "widowed" },
    { tr: "lover" },
];

const moods = [
    { name: "happy", description: "Feeling joyful and content." },
    { name: "sad", description: "Feeling down or unhappy." },
    { name: "angry", description: "Feeling annoyed or upset." },
    { name: "calm", description: "Feeling peaceful and relaxed." },
    { name: "nervous", description: "Feeling anxious or tense." },
    { name: "excited", description: "Feeling thrilled and enthusiastic." },
    { name: "bored", description: "Feeling uninterested or tired of something." },
    { name: "fearful", description: "Feeling scared or worried about something." },
    { name: "confident", description: "Feeling self-assured and positive." },
    { name: "curious", description: "Eager to learn or know more about something." },
    { name: "hopeful", description: "Feeling optimistic about the future." },
    { name: "frustrated", description: "Feeling irritated or annoyed due to obstacles." },
    { name: "lonely", description: "Feeling isolated or missing companionship." },
    { name: "grateful", description: "Feeling thankful and appreciative." },
    { name: "jealous", description: "Feeling envious of someone or something." },
    { name: "guilty", description: "Feeling regretful or responsible for wrongdoing." },
    { name: "apathetic", description: "Feeling indifferent or lacking emotion." },
    { name: "relieved", description: "Feeling a sense of ease after a problem is resolved." },
    { name: "proud", description: "Feeling satisfaction about achievements." },
    { name: "ashamed", description: "Feeling embarrassed or guilty about something." },
];

const characterTraits = [
    { name: "brave", description: "Courageous and willing to take risks." },
    { name: "kind", description: "Compassionate and caring for others." },
    { name: "greedy", description: "Focused on acquiring material wealth." },
    { name: "wise", description: "Possesses deep understanding and insight." },
    { name: "loyal", description: "Faithful to friends or obligations." },
    { name: "cunning", description: "Skilled in achieving goals through cleverness or deceit." },
    { name: "generous", description: "Willing to give and share with others." },
    { name: "arrogant", description: "Overly proud and dismissive of others." },
    { name: "honest", description: "Truthful and sincere." },
    { name: "ambitious", description: "Driven by a strong desire to achieve success." },
    { name: "patient", description: "Able to endure delays or problems without frustration." },
    { name: "impatient", description: "Eager to act or react quickly, often without waiting." },
    { name: "selfish", description: "Focused on one's own needs and desires over others'." },
    { name: "charismatic", description: "Charming and able to inspire others." },
    { name: "empathetic", description: "Able to understand and share the feelings of others." },
    { name: "timid", description: "Shy and lacking confidence." },
    { name: "stubborn", description: "Unwilling to change one's attitude or opinion." },
    { name: "resourceful", description: "Able to find quick and clever solutions to problems." },
    { name: "reckless", description: "Acting without considering the consequences." },
    { name: "disciplined", description: "Able to control oneself and follow rules." },
    { name: "optimistic", description: "Expecting the best possible outcome." },
    { name: "pessimistic", description: "Expecting the worst possible outcome." },
    { name: "manipulative", description: "Skilled at influencing others for one's benefit." },
    { name: "independent", description: "Self-reliant and not needing others' help." },
    { name: "dependent", description: "Relying on others for support or assistance." },
    { name: "adventurous", description: "Willing to take risks and seek new experiences." },
    { name: "humble", description: "Modest and not overly proud of oneself." },
    { name: "vengeful", description: "Driven by a desire to seek revenge." },
    { name: "pragmatic", description: "Focused on practical and realistic approaches." },
    { name: "idealistic", description: "Guided by ideals and principles rather than practicality." },
];

const promotionalGifts = [
    { name: "Gold Coin", description: "A shiny gold coin as a token of appreciation.", value: 100 },
    { name: "Silk Scarf", description: "A luxurious silk scarf with elegant patterns.", value: 50 },
    { name: "Exotic Perfume", description: "A rare and enchanting fragrance.", value: 200 },
    { name: "Crystal Pendant", description: "A beautiful pendant made of pure crystal.", value: 150 },
    { name: "Leather Journal", description: "A high-quality leather-bound journal.", value: 75 },
    { name: "Fine Wine", description: "An exquisite bottle of fine wine.", value: 120 },
    { name: "Artisan Chocolate", description: "A box of handcrafted chocolates.", value: 40 },
    { name: "Pearl Necklace", description: "A stunning necklace made with real pearls.", value: 300 },
    { name: "Rare Painting", description: "A rare painting by a renowned artist.", value: 500 },
    { name: "Silver Watch", description: "An elegant silver wristwatch.", value: 250 },
    { name: "Cat", description: "A cuddly and affectionate companion.", value: 70 },
    { name: "Dog", description: "A loyal and loving pet.", value: 150 },
    { name: "Horse", description: "A majestic animal for riding or companionship.", value: 1000 },
];

const promotionalGiftTraitLinks = [
    { gift: "Gold Coin", trait: "brave", suitability: 3 },
    { gift: "Gold Coin", trait: "kind", suitability: 2 },
    { gift: "Gold Coin", trait: "greedy", suitability: 5 },
    { gift: "Gold Coin", trait: "wise", suitability: 3 },
    { gift: "Gold Coin", trait: "loyal", suitability: 2 },
    { gift: "Silk Scarf", trait: "brave", suitability: 2 },
    { gift: "Silk Scarf", trait: "kind", suitability: 5 },
    { gift: "Silk Scarf", trait: "greedy", suitability: 3 },
    { gift: "Silk Scarf", trait: "wise", suitability: 4 },
    { gift: "Silk Scarf", trait: "loyal", suitability: 3 },
    { gift: "Exotic Perfume", trait: "brave", suitability: 2 },
    { gift: "Exotic Perfume", trait: "kind", suitability: 3 },
    { gift: "Exotic Perfume", trait: "greedy", suitability: 4 },
    { gift: "Exotic Perfume", trait: "wise", suitability: 3 },
    { gift: "Exotic Perfume", trait: "loyal", suitability: 1 },
    { gift: "Crystal Pendant", trait: "brave", suitability: 4 },
    { gift: "Crystal Pendant", trait: "kind", suitability: 4 },
    { gift: "Crystal Pendant", trait: "greedy", suitability: 3 },
    { gift: "Crystal Pendant", trait: "wise", suitability: 5 },
    { gift: "Crystal Pendant", trait: "loyal", suitability: 4 },
    { gift: "Leather Journal", trait: "brave", suitability: 3 },
    { gift: "Leather Journal", trait: "kind", suitability: 3 },
    { gift: "Leather Journal", trait: "greedy", suitability: 2 },
    { gift: "Leather Journal", trait: "wise", suitability: 5 },
    { gift: "Leather Journal", trait: "loyal", suitability: 3 },
    { gift: "Cat", trait: "brave", suitability: 2 },
    { gift: "Cat", trait: "kind", suitability: 5 },
    { gift: "Cat", trait: "greedy", suitability: 2 },
    { gift: "Cat", trait: "wise", suitability: 3 },
    { gift: "Cat", trait: "loyal", suitability: 4 },
    { gift: "Dog", trait: "brave", suitability: 4 },
    { gift: "Dog", trait: "kind", suitability: 4 },
    { gift: "Dog", trait: "greedy", suitability: 1 },
    { gift: "Dog", trait: "wise", suitability: 3 },
    { gift: "Dog", trait: "loyal", suitability: 5 },
    { gift: "Horse", trait: "brave", suitability: 5 },
    { gift: "Horse", trait: "kind", suitability: 3 },
    { gift: "Horse", trait: "greedy", suitability: 2 },
    { gift: "Horse", trait: "wise", suitability: 4 },
    { gift: "Horse", trait: "loyal", suitability: 4 },
];

const promotionalGiftMoodLinks = [
    { gift: "Gold Coin", mood: "happy", suitability: 5 },
    { gift: "Gold Coin", mood: "sad", suitability: 1 },
    { gift: "Gold Coin", mood: "angry", suitability: 2 },
    { gift: "Gold Coin", mood: "calm", suitability: 3 },
    { gift: "Gold Coin", mood: "nervous", suitability: 3 },
    { gift: "Silk Scarf", mood: "happy", suitability: 4 },
    { gift: "Silk Scarf", mood: "sad", suitability: 3 },
    { gift: "Silk Scarf", mood: "angry", suitability: 2 },
    { gift: "Silk Scarf", mood: "calm", suitability: 5 },
    { gift: "Silk Scarf", mood: "nervous", suitability: 4 },
    { gift: "Exotic Perfume", mood: "happy", suitability: 5 },
    { gift: "Exotic Perfume", mood: "sad", suitability: 2 },
    { gift: "Exotic Perfume", mood: "angry", suitability: 1 },
    { gift: "Exotic Perfume", mood: "calm", suitability: 3 },
    { gift: "Exotic Perfume", mood: "nervous", suitability: 5 },
    { gift: "Crystal Pendant", mood: "happy", suitability: 4 },
    { gift: "Crystal Pendant", mood: "sad", suitability: 2 },
    { gift: "Crystal Pendant", mood: "angry", suitability: 2 },
    { gift: "Crystal Pendant", mood: "calm", suitability: 4 },
    { gift: "Crystal Pendant", mood: "nervous", suitability: 3 },
    { gift: "Leather Journal", mood: "happy", suitability: 3 },
    { gift: "Leather Journal", mood: "sad", suitability: 3 },
    { gift: "Leather Journal", mood: "angry", suitability: 1 },
    { gift: "Leather Journal", mood: "calm", suitability: 4 },
    { gift: "Leather Journal", mood: "nervous", suitability: 2 },
    { gift: "Cat", mood: "happy", suitability: 5 },
    { gift: "Cat", mood: "sad", suitability: 4 },
    { gift: "Cat", mood: "angry", suitability: 2 },
    { gift: "Cat", mood: "calm", suitability: 5 },
    { gift: "Cat", mood: "nervous", suitability: 3 },
    { gift: "Dog", mood: "happy", suitability: 5 },
    { gift: "Dog", mood: "sad", suitability: 3 },
    { gift: "Dog", mood: "angry", suitability: 4 },
    { gift: "Dog", mood: "calm", suitability: 4 },
    { gift: "Dog", mood: "nervous", suitability: 3 },
    { gift: "Horse", mood: "happy", suitability: 4 },
    { gift: "Horse", mood: "sad", suitability: 3 },
    { gift: "Horse", mood: "angry", suitability: 2 },
    { gift: "Horse", mood: "calm", suitability: 5 },
    { gift: "Horse", mood: "nervous", suitability: 4 },
];

const houseTypes = [
    { labelTr: 'Unter der Brücke', abbr: 'under_bridge', cost: 0, position: 1, minimumTitle: 'noncivil' },
    { labelTr: 'Strohhütte', abbr: 'straw_hut', cost: 100, position: 2, minimumTitle: 'noncivil' },
    { labelTr: 'Holzhaus', abbr: 'wooden_house', cost: 5000, position: 3, minimumTitle: 'civil' },
    { labelTr: 'Hinterhofzimmer', abbr: 'backyard_room', cost: 75000, position: 4, minimumTitle: 'civil' },
    { labelTr: 'Kleines Familienhaus', abbr: 'family_house', cost: 273000, position: 5, minimumTitle: 'sir' },
    { labelTr: 'Stadthaus', abbr: 'townhouse', cost: 719432, position: 6, minimumTitle: 'townlord' },
    { labelTr: 'Villa', abbr: 'villa', cost: 3500000, position: 7, minimumTitle: 'knight' },
    { labelTr: 'Herrenhaus', abbr: 'mansion', cost: 18000000, position: 8, minimumTitle: 'ruler' },
    { labelTr: 'Schloss', abbr: 'castle', cost: 500000000, position: 9, minimumTitle: 'prince-regent' },
];

const partyTypes = [
    { labelTr: 'wedding', cost: 50, forMarriage: true, reputationGrowth: 5 },
    { labelTr: 'ball', cost: 250, forMarriage: false, reputationGrowth: 7 },
    { labelTr: 'town fair', cost: 1000, forMarriage: false, reputationGrowth: 10 },
    { labelTr: 'royal feast', cost: 50000, forMarriage: false, reputationGrowth: 25 },
];

const musicTypes = [
    { type: 'none', cost: 0, reputationGrowth: 0 },
    { type: 'bard', cost: 100, reputationGrowth: 2 },
    { type: 'villageBand', cost: 2500, reputationGrowth: 5 },
    { type: 'chamberOrchestra', cost: 12000, reputationGrowth: 10 },
    { type: 'symphonyOrchestra', cost: 37000, reputationGrowth: 15 },
    { type: 'symphonyOrchestraWithChorusAndSolists', cost: 500000, reputationGrowth: 25 },
];

const banquetteTypes = [
    { type: 'bread', cost: 5, reputationGrowth: 0 },
    { type: 'roastWithBeer', cost: 200, reputationGrowth: 5 },
    { type: 'poultryWithVegetablesAndWine', cost: 5000, reputationGrowth: 10 },
    { type: 'extensiveBuffet', cost: 100000, reputationGrowth: 20 }
];

const learnerTypes = [
    { tr: 'self', },
    { tr: 'children', },
    { tr: 'director', },
];

const vehicleTypes = [
    // build times (in minutes): 60, 90, 180, 300, 720, 120, 1440
    { tr: 'cargo_cart',          name: 'Lastkarren',             cost: 100,  capacity: 20,  transportMode: 'land',  speed: 1, buildTimeMinutes: 60 },
    { tr: 'ox_cart',             name: 'Ochsenkarren',           cost: 200,  capacity: 50,  transportMode: 'land',  speed: 2, buildTimeMinutes: 90 },
    { tr: 'small_carriage',      name: 'kleine Pferdekutsche',   cost: 300,  capacity: 35,  transportMode: 'land',  speed: 3, buildTimeMinutes: 180 },
    { tr: 'large_carriage',      name: 'große Pferdekutsche',    cost: 1000, capacity: 100, transportMode: 'land',  speed: 3, buildTimeMinutes: 300 },
    { tr: 'four_horse_carriage', name: 'Vierspänner',            cost: 5000, capacity: 200, transportMode: 'land',  speed: 4, buildTimeMinutes: 720 },
    { tr: 'raft',                name: 'Floß',                   cost: 100,  capacity: 25,  transportMode: 'water', speed: 1, buildTimeMinutes: 120 },
    { tr: 'sailing_ship',        name: 'Segelschiff',            cost: 500,  capacity: 200, transportMode: 'water', speed: 3, buildTimeMinutes: 1440 },
];

const politicalOfficeBenefitTypes = [
    { tr: 'salary' },
    { tr: 'reputation' },
    { tr: 'influence' },
    { tr: 'access_level' },
    { tr: 'housing_allowance' },
    { tr: 'tax_exemption' },
    { tr: 'guard_protection' },
    { tr: 'court_immunity' },
    { tr: 'set_regionl_tax' },
];

const politicalOffices = [
    { tr: "assessor", seatsPerRegion: 10, regionType: "city", termLength: 5 },
    { tr: "councillor", seatsPerRegion: 7, regionType: "city", termLength: 7 },
    { tr: "council", seatsPerRegion: 5, regionType: "city", termLength: 4 },
    { tr: "beadle", seatsPerRegion: 1, regionType: "city", termLength: 6 },
    { tr: "town-clerk", seatsPerRegion: 3, regionType: "city", termLength: 10 },
    { tr: "mayor", seatsPerRegion: 1, regionType: "city", termLength: 3 },
    { tr: "master-builder", seatsPerRegion: 10, regionType: "county", termLength: 10 },
    { tr: "village-major", seatsPerRegion: 6, regionType: "county", termLength: 5 },
    { tr: "judge", seatsPerRegion: 3, regionType: "county", termLength: 8 },
    { tr: "bailif", seatsPerRegion: 1, regionType: "county", termLength: 4 },
    { tr: "taxman", seatsPerRegion: 8, regionType: "shire", termLength: 5 },
    { tr: "sheriff", seatsPerRegion: 5, regionType: "shire", termLength: 8 },
    { tr: "consultant", seatsPerRegion: 3, regionType: "shire", termLength: 9 },
    { tr: "treasurer", seatsPerRegion: 1, regionType: "shire", termLength: 7 },
    { tr: "hangman", seatsPerRegion: 9, regionType: "markgravate", termLength: 5 },
    { tr: "territorial-council", seatsPerRegion: 6, regionType: "markgravate", termLength: 6 },
    { tr: "territorial-council-speaker", seatsPerRegion: 4, regionType: "markgravate", termLength: 8 },
    { tr: "ruler-consultant", seatsPerRegion: 1, regionType: "markgravate", termLength: 3 },
    { tr: "state-administrator", seatsPerRegion: 7, regionType: "duchy", termLength: 3 },
    { tr: "super-state-administrator", seatsPerRegion: 5, regionType: "duchy", termLength: 6 },
    { tr: "governor", seatsPerRegion: 1, regionType: "duchy", termLength: 5 },
    { tr: "ministry-helper", seatsPerRegion: 12, regionType: "country", termLength: 4 },
    { tr: "minister", seatsPerRegion: 3, regionType: "country", termLength: 4 },
    { tr: "chancellor", seatsPerRegion: 1, regionType: "country", termLength: 4 }
];

const politicalOfficePrerequisites = [
    {
        officeTr: "assessor",
        prerequisite: {
            titles: [
                "civil", "sir", "townlord", "by", "landlord", "knight",
                "baron", "count", "palsgrave", "margrave", "landgrave",
                "ruler", "elector", "imperial-prince", "duke", "grand-duke",
                "prince-regent", "king"
            ]
        }
    },
    {
        officeTr: "councillor",
        prerequisite: {
            titles: [
                "civil", "sir", "townlord", "by", "landlord", "knight",
                "baron", "count", "palsgrave", "margrave", "landgrave",
                "ruler", "elector", "imperial-prince", "duke", "grand-duke",
                "prince-regent", "king"
            ],
            jobs: ["assessor"]
        }
    },
    {
        officeTr: "council",
        prerequisite: {
            titles: [
                "civil", "sir", "townlord", "by", "landlord", "knight",
                "baron", "count", "palsgrave", "margrave", "landgrave",
                "ruler", "elector", "imperial-prince", "duke", "grand-duke",
                "prince-regent", "king"
            ],
            jobs: ["councillor"]
        }
    },
    {
        officeTr: "beadle",
        prerequisite: {
            titles: [
                "sir", "townlord", "by", "landlord", "knight", "baron",
                "count", "palsgrave", "margrave", "landgrave", "ruler",
                "elector", "imperial-prince", "duke", "grand-duke", "prince-regent", "king"
            ],
            jobs: ["council"]
        }
    },
    {
        officeTr: "town-clerk",
        prerequisite: {
            titles: [
                "sir", "townlord", "by", "landlord", "knight", "baron",
                "count", "palsgrave", "margrave", "landgrave", "ruler",
                "elector", "imperial-prince", "duke", "grand-duke", "prince-regent", "king"
            ],
            jobs: ["council"]
        }
    },
    {
        officeTr: "mayor",
        prerequisite: {
            titles: [
                "townlord", "by", "landlord", "knight", "baron", "count",
                "palsgrave", "margrave", "landgrave", "ruler", "elector",
                "imperial-prince", "duke", "grand-duke", "prince-regent", "king"
            ],
            jobs: ["beadle", "town-clerk"]
        }
    },
    {
        officeTr: "master-builder",
        prerequisite: {
            titles: [
                "by", "landlord", "knight", "baron", "count", "palsgrave",
                "margrave", "landgrave", "ruler", "elector", "imperial-prince",
                "duke", "grand-duke", "prince-regent", "king"
            ],
            jobs: ["mayor"]
        }
    },
    {
        officeTr: "village-major",
        prerequisite: {
            titles: [
                "by", "landlord", "knight", "baron", "count", "palsgrave",
                "margrave", "landgrave", "ruler", "elector", "imperial-prince",
                "duke", "grand-duke", "prince-regent", "king"
            ],
            jobs: ["master-builder"]
        }
    },
    {
        officeTr: "judge",
        prerequisite: {
            titles: [
                "landlord", "knight", "baron", "count", "palsgrave", "margrave",
                "landgrave", "ruler", "elector", "imperial-prince", "duke",
                "grand-duke", "prince-regent", "king"
            ],
            jobs: ["village-major"]
        }
    },
    {
        officeTr: "bailif",
        prerequisite: {
            titles: [
                "landlord", "knight", "baron", "count", "palsgrave", "margrave",
                "landgrave", "ruler", "elector", "imperial-prince", "duke",
                "grand-duke", "prince-regent", "king"
            ],
            jobs: ["judge"]
        }
    },
    {
        officeTr: "taxman",
        prerequisite: {
            titles: [
                "knight", "baron", "count", "palsgrave", "margrave", "landgrave",
                "ruler", "elector", "imperial-prince", "duke", "grand-duke", "prince-regent", "king"
            ],
            jobs: ["bailif"]
        }
    },
    {
        officeTr: "sheriff",
        prerequisite: {
            titles: [
                "baron", "count", "palsgrave", "margrave", "landgrave", "ruler",
                "elector", "imperial-prince", "duke", "grand-duke", "prince-regent", "king"
            ],
            jobs: ["taxman"]
        }
    },
    {
        officeTr: "consultant",
        prerequisite: {
            titles: [
                "baron", "count", "palsgrave", "margrave", "landgrave", "ruler",
                "elector", "imperial-prince", "duke", "grand-duke", "prince-regent", "king"
            ],
            jobs: ["sheriff"]
        }
    },
    {
        officeTr: "treasurer",
        prerequisite: {
            titles: [
                "count", "palsgrave", "margrave", "landgrave", "ruler", "elector",
                "imperial-prince", "duke", "grand-duke", "prince-regent", "king"
            ],
            jobs: ["consultant"]
        }
    },
    {
        officeTr: "hangman",
        prerequisite: {
            titles: [
                "count", "palsgrave", "margrave", "landgrave", "ruler", "elector",
                "imperial-prince", "duke", "grand-duke", "prince-regent", "king"
            ],
            jobs: ["consultant"]
        }
    },
    {
        officeTr: "territorial-council",
        prerequisite: {
            titles: [
                "palsgrave", "margrave", "landgrave", "ruler", "elector", "imperial-prince",
                "duke", "grand-duke", "prince-regent", "king"
            ],
            jobs: ["treasurer", "hangman"]
        }
    },
    {
        officeTr: "territorial-council-speaker",
        prerequisite: {
            titles: [
                "margrave", "landgrave", "ruler", "elector", "imperial-prince", "duke",
                "grand-duke", "prince-regent", "king"
            ],
            jobs: ["territorial-council"]
        }
    },
    {
        officeTr: "ruler-consultant",
        prerequisite: {
            titles: [
                "landgrave", "ruler", "elector", "imperial-prince", "duke", "grand-duke",
                "prince-regent", "king"
            ],
            jobs: ["territorial-council-speaker"]
        }
    },
    {
        officeTr: "state-administrator",
        prerequisite: {
            titles: [
                "ruler", "elector", "imperial-prince", "duke", "grand-duke", "prince-regent", "king"
            ],
            jobs: ["ruler-consultant"]
        }
    },
    {
        officeTr: "super-state-administrator",
        prerequisite: {
            titles: [
                "elector", "imperial-prince", "duke", "grand-duke", "prince-regent", "king"
            ],
            jobs: ["state-administrator"]
        }
    },
    {
        officeTr: "governor",
        prerequisite: {
            titles: [
                "imperial-prince", "duke", "grand-duke", "prince-regent", "king"
            ],
            jobs: ["super-state-administrator"]
        }
    },
    {
        officeTr: "ministry-helper",
        prerequisite: {
            titles: [
                "grand-duke", "prince-regent", "king"
            ],
            jobs: ["governor"]
        }
    },
    {
        officeTr: "minister",
        prerequisite: {
            titles: [
                "prince-regent", "king"
            ],
            jobs: ["ministry-helper"]
        }
    },
    {
        officeTr: "chancellor",
        prerequisite: {
            titles: [
                "prince-regent", "king"
            ],
            jobs: ["minister"]
        }
    }
];

const undergroundTypes = [
    {
        "tr": "spyin",
        "cost": 3000
    },
    {
        "tr": "assassin",
        "cost": 5000
    },
    {
        "tr": "sabotage",
        "cost": 10000
    },
    {
        "tr": "corrupt_politician",
        "cost": 15000
    },
    {
        "tr": "rob",
        "cost": 500
    },
];

{
    const giftNames = promotionalGifts.map(g => g.name);
    const traitNames = characterTraits.map(t => t.name);

    giftNames.forEach(giftName => {
        traitNames.forEach(traitName => {
            if (!promotionalGiftTraitLinks.some(l => l.gift === giftName && l.trait === traitName)) {
                promotionalGiftTraitLinks.push({
                    gift: giftName,
                    trait: traitName,
                    suitability: Math.floor(Math.random() * 5) + 1,
                });
            }
        });
    });
}

{
    const giftNames = promotionalGifts.map(g => g.name);
    const moodNames = moods.map(m => m.name);

    giftNames.forEach(giftName => {
        moodNames.forEach(moodName => {
            if (!promotionalGiftMoodLinks.some(l => l.gift === giftName && l.mood === moodName)) {
                promotionalGiftMoodLinks.push({
                    gift: giftName,
                    mood: moodName,
                    suitability: Math.floor(Math.random() * 5) + 1,
                });
            }
        });
    });
}

const initializeFalukantTypeRegions = async () => {
    for (const regionType of regionTypeTrs) {
        const [regionTypeRecord] = await RegionType.findOrCreate({
            where: { labelTr: regionType },
            defaults: {
                parentId: regionTypes[regionTypes.length - 1]?.id
            }
        });

        regionTypes.push(regionTypeRecord);
    }
};

const findRegionTypeObjectByRegionType = async (regionType) => {
    return regionTypes.find(region => region.labelTr === regionType) || null;
};

const findRegionObjectByLabelTr = async (labelTr) => {
    return await RegionData.findOne({ where: { name: labelTr } });
};

export const initializeFalukantRegions = async () => {
    for (const region of regions) {
        const regionType = await findRegionTypeObjectByRegionType(region.regionType);
        if (!regionType) {
            console.error(`Region type not found for: ${region.regionType}`);
            continue;
        }
        const parentRegion = region.parentTr
            ? await findRegionObjectByLabelTr(region.parentTr)
            : null;
        if (region.parentTr && !parentRegion) {
            console.error(`Parent region not found for: ${region.parentTr}`);
            continue;
        }
    if (falukantDebug) console.log('[Falukant] Region', region.labelTr, 'type', regionType.labelTr, 'parent', parentRegion?.name);
        await RegionData.findOrCreate({
            where: { name: region.labelTr },
            defaults: {
                regionTypeId: regionType.id,
                parentId: parentRegion?.id || null,
                map: parentRegion?.map || {},
            }
        });
    }
};

export const initializeFalukantRelationships = async () => {
    for (const relationship of relationships) {
        await Relationship.findOrCreate({
            where: { tr: relationship.tr },
            defaults: {}
        });
    }
};

export const initializeFalukantMoods = async () => {
    for (const mood of moods) {
        await Mood.findOrCreate({
            where: { tr: mood.name },
        });
    }
};


export const initializeFalukantCharacterTraits = async () => {
    for (const trait of characterTraits) {
        await CharacterTrait.findOrCreate({
            where: { tr: trait.name },
        });
    }
};

export const initializeFalukantPromotionalGifts = async () => {
    for (const gift of promotionalGifts) {
        await PromotionalGift.findOrCreate({
            where: { name: gift.name },
            defaults: {
                description: gift.description,
                value: gift.value,
            },
        });
    }
};

export const initializePromotionalGiftTraitLinks = async () => {
    const giftRows = await PromotionalGift.findAll({ attributes: ['id','name'], raw: true });
    const traitRows = await CharacterTrait.findAll({ attributes: ['id','tr'], raw: true });
    const giftMap = new Map(giftRows.map(g=>[g.name,g.id]));
    const traitMap = new Map(traitRows.map(t=>[t.tr,t.id]));
    let created = 0, updated = 0, skipped = 0;
    for (const link of promotionalGiftTraitLinks) {
        const giftId = giftMap.get(link.gift);
        const traitId = traitMap.get(link.trait);
        if (giftId == null || traitId == null) { skipped++; continue; }
        try {
            const [record, wasCreated] = await PromotionalGiftCharacterTrait.findOrCreate({
                where: { giftId, traitId },
                defaults: { giftId, traitId, suitability: link.suitability }
            });
            if (wasCreated) { created++; }
            else if (record.suitability !== link.suitability) { record.suitability = link.suitability; await record.save(); updated++; }
        } catch (e) {
            if (falukantDebug) console.error('[Falukant] TraitLink Fehler (Model)', { giftId, traitId, error: e.message });
            // Fallback RAW Insert/Upsert
            try {
                await sequelize.query('INSERT INTO falukant_predefine.promotional_gift_character_trait (gift_id, trait_id, suitability) VALUES (:g,:t,:s) ON CONFLICT (gift_id, trait_id) DO UPDATE SET suitability = EXCLUDED.suitability', {
                    replacements: { g: giftId, t: traitId, s: link.suitability }
                });
                created++;
            } catch (rawErr) {
                console.error('[Falukant] TraitLink RAW fail', { giftId, traitId, error: rawErr.message });
                throw rawErr;
            }
        }
    }
    console.log(`[Falukant] TraitLinks neu=${created} upd=${updated}${skipped?` skip=${skipped}`:''}`);
};

export const initializePromotionalGiftMoodLinks = async () => {
    // Diagnose: Zähle vorhandene Gifts & Moods bevor Links erstellt werden
    try {
        const totalGifts = await PromotionalGift.count();
        const totalMoods = await Mood.count();
    if (falukantDebug) console.log(`[Falukant] MoodLinks start gifts=${totalGifts} moods=${totalMoods} defs=${promotionalGiftMoodLinks.length}`);
    } catch (e) {
    if (falukantDebug) console.warn('[Falukant] MoodLinks count fail:', e.message);
    }
    // Prefetch Maps um Lookup stabil zu machen und potentielle Race-Conditions auszuschließen
    const giftRows = await PromotionalGift.findAll({ attributes: ['id', 'name'], raw: true });
    const moodRows = await Mood.findAll({ attributes: ['id', 'tr'], raw: true });
    const giftMap = new Map(giftRows.map(g => [g.name, g.id]));
    const moodMap = new Map(moodRows.map(m => [m.tr, m.id]));
    // (logging minimiert)

    let nullIdIssues = 0;
    let createdCount = 0;
    let updatedCount = 0;
    const anomalies = [];
    for (const link of promotionalGiftMoodLinks) {
        const giftId = giftMap.get(link.gift);
        const moodId = moodMap.get(link.mood);
        if (giftId == null || moodId == null) {
            nullIdIssues++;
            anomalies.push({ link, giftId, moodId });
            if (falukantDebug && nullIdIssues <= 10) console.error('[Falukant] MoodLink Lookup miss', { link, giftId, moodId });
            continue;
        }
        try {
            // Verwende Model API mit field-Mapping (giftId -> gift_id) jetzt vorhanden im Model
            const [record, created] = await PromotionalGiftMood.findOrCreate({
                where: { giftId, moodId },
                defaults: { suitability: link.suitability }
            });
            if (!created && record.suitability !== link.suitability) {
                record.suitability = link.suitability;
                await record.save();
                updatedCount++;
            } else if (created) {
                createdCount++;
            }
            // kein per-Link Logging mehr
        } catch (err) {
            if (falukantDebug) console.error('[Falukant] MoodLink Fehler (Model)', { link, giftId, moodId, error: err.message });
            // Fallback: versuche noch einmal per RAW (sollte nicht nötig sein)
            try {
                await sequelize.query('INSERT INTO falukant_predefine.promotional_gift_mood (gift_id, mood_id, suitability) VALUES (:g,:m,:s) ON CONFLICT (gift_id, mood_id) DO UPDATE SET suitability = EXCLUDED.suitability', {
                    replacements: { g: giftId, m: moodId, s: link.suitability }
                });
                createdCount++;
                // Fallback erfolgreich (unterdrücktes Detail-Logging)
            } catch (rawErr) {
                console.error('[Falukant] MoodLink RAW fail', { giftId, moodId, error: rawErr.message });
                throw rawErr;
            }
        }
    }
    if (falukantDebug && nullIdIssues > 0) {
        console.warn(`[Falukant] MoodLinks miss=${nullIdIssues} (bis 10 geloggt)`);
        if (anomalies.length) console.warn('[Falukant] MoodLinks Beispiele:', anomalies.slice(0, 3));
    }
    console.log(`[Falukant] MoodLinks neu=${createdCount} upd=${updatedCount}${nullIdIssues?` miss=${nullIdIssues}`:''}`);
};

export const initializeFalukantHouseTypes = async () => {
    for (const ht of houseTypes) {
        try {
            // Finde den minimalen Adelstitel
            const minimumTitle = await TitleOfNobility.findOne({ where: { labelTr: ht.minimumTitle } });
            
            if (!minimumTitle) {
                console.warn(`⚠️  Warnung: Titel '${ht.minimumTitle}' für Haustyp '${ht.abbr}' nicht gefunden. Überspringe...`);
                continue;
            }
            
            const [record, created] = await HouseType.findOrCreate({
                where: { labelTr: ht.abbr },
                defaults: {
                    cost: ht.cost,
                    imageUrl: null,
                    position: ht.position,
                    minimumNobleTitle: minimumTitle.id,
                }
            });
            
            if (created) {
                console.log(`✅ Haustyp '${ht.abbr}' erstellt`);
            }
        } catch (error) {
            console.error(`❌ Fehler beim Erstellen des Haustyps '${ht.abbr}':`, error.message);
            throw error;
        }
    }
};

export const initializeFalukantPartyTypes = async () => {
    for (const pt of partyTypes) {
        const [record, created] = await PartyType.findOrCreate({
            where: { tr: pt.labelTr },
            defaults: {
                cost: pt.cost,
                tr: pt.labelTr,
                forMarriage: pt.forMarriage,
                reputationGrowth: pt.reputationGrowth,
            }
        });
    }
}

export const initializeFalukantMusicTypes = async () => {
    for (const mt of musicTypes) {
        const [record, created] = await MusicType.findOrCreate({
            where: { tr: mt.type },
            defaults: {
                cost: mt.cost,
                tr: mt.type,
                reputationGrowth: mt.reputationGrowth,
            }
        });
    }
}

export const initializeFalukantBanquetteTypes = async () => {
    for (const bt of banquetteTypes) {
        const [record, created] = await BanquetteType.findOrCreate({
            where: { tr: bt.type },
            defaults: {
                tr: bt.type,
                cost: bt.cost,
                reputationGrowth: bt.reputationGrowth,
            }
        });
    }
};

export const initializeLearnerTypes = async () => {
    for (const lt of learnerTypes) {
        const [record, created] = await LearnRecipient.findOrCreate({
            where: { tr: lt.tr },
            defaults: {
                tr: lt.tr,
            }
        });
    }
};

export const initializeVehicleTypes = async () => {
    for (const v of vehicleTypes) {
        const existing = await VehicleType.findOne({ where: { tr: v.tr } });
        if (!existing) {
            await VehicleType.create({
                tr: v.tr,
                cost: v.cost,
                capacity: v.capacity,
                transportMode: v.transportMode,
                speed: v.speed,
                buildTimeMinutes: v.buildTimeMinutes,
            });
        } else {
            // ensure new fields like cost/buildTime are updated if missing
            await existing.update({
                cost: v.cost,
                capacity: v.capacity,
                transportMode: v.transportMode,
                speed: v.speed,
                buildTimeMinutes: v.buildTimeMinutes,
            });
        }
    }
};

export const initializePoliticalOfficeBenefitTypes = async () => {
    for (const benefitType of politicalOfficeBenefitTypes) {
        await PoliticalOfficeBenefitType.findOrCreate({
            where: { tr: benefitType.tr },
        });
    }
    console.log(`[Falukant] PoliticalOfficeBenefitTypes initialisiert: ${politicalOfficeBenefitTypes.length} Typen`);
};

export const initializePoliticalOfficeTypes = async () => {
    for (const po of politicalOffices) {
        await PoliticalOfficeType.findOrCreate({
            where: { name: po.tr },
            defaults: {
                seatsPerRegion: po.seatsPerRegion,
                regionType: po.regionType,
                termLength: po.termLength
            }
        });
    }
};

export const initializePoliticalOfficePrerequisites = async () => {
    let created = 0;
    let existing = 0;
    let skipped = 0;
    for (const prereq of politicalOfficePrerequisites) {
        const office = await PoliticalOfficeType.findOne({ where: { name: prereq.officeTr } });
        if (!office) { skipped++; continue; }
        try {
            const [record, wasCreated] = await PoliticalOfficePrerequisite.findOrCreate({
                where: { officeTypeId: office.id },
                defaults: { officeTypeId: office.id, prerequisite: prereq.prerequisite }
            });
            if (wasCreated) created++; else existing++;
        } catch (e) {
        if (falukantDebug) console.error('[Falukant] OfficePrereq Fehler', { officeId: office?.id, error: e.message });
            // Fehler weiterwerfen um Initialisierung nicht still zu verschlucken
            throw e;
        }
    }
    console.log(`[Falukant] OfficePrereq neu=${created} exist=${existing}${skipped?` skip=${skipped}`:''}`);
};

export const initializeUndergroundTypes = async () => {
    for (const underground of undergroundTypes) {
        await UndergroundType.findOrCreate({
            where: { tr: underground.tr },
            defaults: {
                tr: underground.tr,
                cost: underground.cost
            }
        });
    }
};

// Adelstitel initialisieren (von initializeFalukantPredefines.js verschoben)
export const initializeFalukantTitlesOfNobility = async () => {
    try {
        await TitleOfNobility.bulkCreate([
            { labelTr: "noncivil", level: 1 },
            { labelTr: "civil", level: 2 },
            { labelTr: "sir", level: 3 },
            { labelTr: "townlord", level: 4 },
            { labelTr: "by", level: 5 },
            { labelTr: "landlord", level: 6 },
            { labelTr: "knight", level: 7 },
            { labelTr: "baron", level: 8 },
            { labelTr: "count", level: 9 },
            { labelTr: "palsgrave", level: 10 },
            { labelTr: "margrave", level: 11 },
            { labelTr: "landgrave", level: 12 },
            { labelTr: "ruler", level: 13 },
            { labelTr: "elector", level: 14 },
            { labelTr: "imperial-prince", level: 15 },
            { labelTr: "duke", level: 16 },
            { labelTr: "grand-duke", level: 17 },
            { labelTr: "prince-regent", level: 18 },
            { labelTr: "king", level: 19 },
        ], {
            ignoreDuplicates: true,
        });
        
        console.log(`[Falukant] Adelstitel initialisiert: 19 Titel`);
    } catch (error) {
        console.error('❌ Fehler beim Initialisieren der Falukant-Adelstitel:', error);
        throw error;
    }
};

const weatherTypes = [
    { tr: "sunny" },
    { tr: "cloudy" },
    { tr: "rainy" },
    { tr: "stormy" },
    { tr: "snowy" },
    { tr: "foggy" },
    { tr: "windy" },
    { tr: "clear" }
];

export const initializeFalukantWeatherTypes = async () => {
    try {
        for (const weatherType of weatherTypes) {
            await WeatherType.findOrCreate({
                where: { tr: weatherType.tr },
            });
        }
        console.log(`[Falukant] Wettertypen initialisiert: ${weatherTypes.length} Typen`);
    } catch (error) {
        console.error('❌ Fehler beim Initialisieren der Falukant-Wettertypen:', error);
        throw error;
    }
};

export const initializeFalukantWeathers = async () => {
    try {
        // Hole alle Städte (Regions vom Typ "city")
        const cityRegionType = await RegionType.findOne({ where: { labelTr: 'city' } });
        if (!cityRegionType) {
            console.warn('[Falukant] Kein RegionType "city" gefunden, überspringe Wetter-Initialisierung');
            return;
        }

        const cities = await RegionData.findAll({
            where: { regionTypeId: cityRegionType.id },
            attributes: ['id', 'name']
        });

        // Hole alle Wettertypen
        const allWeatherTypes = await WeatherType.findAll();
        if (allWeatherTypes.length === 0) {
            console.warn('[Falukant] Keine Wettertypen gefunden, überspringe Wetter-Initialisierung');
            return;
        }

        // Weise jeder Stadt zufällig ein Wetter zu
        for (const city of cities) {
            const randomWeatherType = allWeatherTypes[Math.floor(Math.random() * allWeatherTypes.length)];
            await Weather.findOrCreate({
                where: { regionId: city.id },
                defaults: {
                    weatherTypeId: randomWeatherType.id
                }
            });
        }

        console.log(`[Falukant] Wetter für ${cities.length} Städte initialisiert`);
    } catch (error) {
        console.error('❌ Fehler beim Initialisieren der Falukant-Wetter:', error);
        throw error;
    }
};

export const initializeFalukantProductWeatherEffects = async () => {
    try {
        // Hole alle Produkte und Wettertypen
        const products = await ProductType.findAll();
        const weatherTypes = await WeatherType.findAll();
        
        if (products.length === 0 || weatherTypes.length === 0) {
            console.warn('[Falukant] Keine Produkte oder Wettertypen gefunden, überspringe Produkt-Wetter-Effekte');
            return;
        }

        // Erstelle Map für schnellen Zugriff
        const productMap = new Map(products.map(p => [p.labelTr, p.id]));
        const weatherMap = new Map(weatherTypes.map(w => [w.tr, w.id]));

        // Definiere Effekte für jedes Produkt-Wetter-Paar
        // Format: { productLabel: { weatherTr: effectValue } }
        // effectValue: -2 (sehr negativ), -1 (negativ), 0 (neutral), 1 (positiv), 2 (sehr positiv)
        const effects = {
            // Landwirtschaftliche Produkte
            wheat: {
                sunny: 1,      // Gutes Wachstum
                cloudy: 0,
                rainy: 2,      // Wasser ist essentiell
                stormy: -1,    // Kann Ernte beschädigen
                snowy: -2,     // Kein Wachstum
                foggy: 0,
                windy: 0,
                clear: 1
            },
            grain: {
                sunny: 1,
                cloudy: 0,
                rainy: 2,
                stormy: -1,
                snowy: -2,
                foggy: 0,
                windy: 0,
                clear: 1
            },
            carrot: {
                sunny: 1,
                cloudy: 0,
                rainy: 2,
                stormy: -1,
                snowy: -2,
                foggy: 0,
                windy: 0,
                clear: 1
            },
            fish: {
                sunny: 0,
                cloudy: 0,
                rainy: 0,
                stormy: -2,    // Gefährlich zu fischen
                snowy: -1,     // Kaltes Wasser
                foggy: -1,     // Schlechte Sicht
                windy: -1,     // Schwierig zu fischen
                clear: 1
            },
            meat: {
                sunny: -1,     // Kann verderben
                cloudy: 0,
                rainy: -1,     // Feucht
                stormy: -2,
                snowy: 1,      // Kühlt
                foggy: 0,
                windy: 0,
                clear: 0
            },
            leather: {
                sunny: -1,     // Kann austrocknen
                cloudy: 0,
                rainy: -1,     // Feucht
                stormy: -2,
                snowy: 1,      // Kühlt
                foggy: 0,
                windy: 0,
                clear: 0
            },
            wood: {
                sunny: 1,      // Trocknet gut
                cloudy: 0,
                rainy: -1,     // Feucht
                stormy: -2,    // Kann beschädigt werden
                snowy: 0,
                foggy: -1,     // Feucht
                windy: 0,
                clear: 1
            },
            stone: {
                sunny: 0,
                cloudy: 0,
                rainy: 0,
                stormy: 0,
                snowy: 0,
                foggy: 0,
                windy: 0,
                clear: 0
            },
            milk: {
                sunny: -1,     // Kann sauer werden
                cloudy: 0,
                rainy: 0,
                stormy: -1,
                snowy: 1,      // Kühlt
                foggy: 0,
                windy: 0,
                clear: 0
            },
            cheese: {
                sunny: -1,
                cloudy: 0,
                rainy: -1,     // Feucht
                stormy: -1,
                snowy: 1,      // Kühlt
                foggy: 0,
                windy: 0,
                clear: 0
            },
            bread: {
                sunny: 0,
                cloudy: 0,
                rainy: -1,     // Feucht
                stormy: -1,
                snowy: 0,
                foggy: -1,     // Feucht
                windy: 0,
                clear: 0
            },
            beer: {
                sunny: 0,
                cloudy: 0,
                rainy: 0,
                stormy: 0,
                snowy: 1,      // Kühlt
                foggy: 0,
                windy: 0,
                clear: 0
            },
            iron: {
                sunny: 0,
                cloudy: 0,
                rainy: -1,     // Rost
                stormy: -2,     // Rost
                snowy: 0,
                foggy: -1,     // Feucht
                windy: 0,
                clear: 0
            },
            copper: {
                sunny: 0,
                cloudy: 0,
                rainy: -1,     // Oxidation
                stormy: -2,
                snowy: 0,
                foggy: -1,
                windy: 0,
                clear: 0
            },
            spices: {
                sunny: 0,
                cloudy: 0,
                rainy: -1,     // Feucht
                stormy: -1,
                snowy: 0,
                foggy: -1,     // Feucht
                windy: 0,
                clear: 0
            },
            salt: {
                sunny: 1,      // Trocknet gut
                cloudy: 0,
                rainy: -2,     // Löst sich auf
                stormy: -2,
                snowy: 0,
                foggy: -1,     // Feucht
                windy: 0,
                clear: 1
            },
            sugar: {
                sunny: 0,
                cloudy: 0,
                rainy: -2,     // Löst sich auf
                stormy: -2,
                snowy: 0,
                foggy: -1,     // Feucht
                windy: 0,
                clear: 0
            },
            vinegar: {
                sunny: 1,      // Heißes Wetter fördert Gärung
                cloudy: 0,
                rainy: 0,
                stormy: 0,
                snowy: -1,      // Kaltes Wetter hemmt Gärung
                foggy: 0,
                windy: 0,
                clear: 1       // Heißes Wetter fördert Gärung
            },
            cotton: {
                sunny: 1,      // Trocknet gut
                cloudy: 0,
                rainy: -1,     // Feucht
                stormy: -2,
                snowy: 0,
                foggy: -1,     // Feucht
                windy: 0,
                clear: 1
            },
            wine: {
                sunny: 0,
                cloudy: 0,
                rainy: 0,
                stormy: 0,
                snowy: 1,      // Kühlt
                foggy: 0,
                windy: 0,
                clear: 0
            },
            gold: {
                sunny: 0,
                cloudy: 0,
                rainy: 0,
                stormy: 0,
                snowy: 0,
                foggy: 0,
                windy: 0,
                clear: 0
            },
            diamond: {
                sunny: 0,
                cloudy: 0,
                rainy: 0,
                stormy: 0,
                snowy: 0,
                foggy: 0,
                windy: 0,
                clear: 0
            },
            furniture: {
                sunny: 0,
                cloudy: 0,
                rainy: -1,     // Feucht
                stormy: -2,
                snowy: 0,
                foggy: -1,     // Feucht
                windy: 0,
                clear: 0
            },
            clothing: {
                sunny: 0,
                cloudy: 0,
                rainy: -1,     // Feucht
                stormy: -2,
                snowy: 0,
                foggy: -1,     // Feucht
                windy: 0,
                clear: 0
            },
            jewelry: {
                sunny: 0,
                cloudy: 0,
                rainy: -2,     // Kann beschädigt werden
                stormy: -2,
                snowy: 0,
                foggy: -1,     // Feucht
                windy: 0,
                clear: 0
            },
            painting: {
                sunny: -1,     // Kann verblassen
                cloudy: 0,
                rainy: -2,     // Feucht
                stormy: -2,
                snowy: 0,
                foggy: -1,     // Feucht
                windy: 0,
                clear: -1
            },
            book: {
                sunny: -1,     // Kann verblassen
                cloudy: 0,
                rainy: -2,     // Feucht
                stormy: -2,
                snowy: 0,
                foggy: -1,     // Feucht
                windy: 0,
                clear: -1
            },
            weapon: {
                sunny: 0,
                cloudy: 0,
                rainy: -1,     // Rost
                stormy: -2,     // Rost
                snowy: 0,
                foggy: -1,     // Feucht
                windy: 0,
                clear: 0
            },
            armor: {
                sunny: 0,
                cloudy: 0,
                rainy: -1,     // Rost
                stormy: -2,     // Rost
                snowy: 0,
                foggy: -1,     // Feucht
                windy: 0,
                clear: 0
            },
            shield: {
                sunny: 0,
                cloudy: 0,
                rainy: -1,     // Rost
                stormy: -2,     // Rost
                snowy: 0,
                foggy: -1,     // Feucht
                windy: 0,
                clear: 0
            },
            horse: {
                sunny: 1,      // Gutes Wetter
                cloudy: 0,
                rainy: -1,     // Nass
                stormy: -2,     // Angst
                snowy: -1,     // Kalt
                foggy: 0,
                windy: 0,
                clear: 1
            },
            ox: {
                sunny: 1,      // Gutes Wetter
                cloudy: 0,
                rainy: -1,     // Nass
                stormy: -2,     // Angst
                snowy: -1,     // Kalt
                foggy: 0,
                windy: 0,
                clear: 1
            }
        };

        // Erstelle alle Produkt-Wetter-Effekte
        const effectEntries = [];
        for (const [productLabel, weatherEffects] of Object.entries(effects)) {
            const productId = productMap.get(productLabel);
            if (!productId) {
                console.warn(`[Falukant] Produkt "${productLabel}" nicht gefunden, überspringe`);
                continue;
            }

            for (const [weatherTr, effectValue] of Object.entries(weatherEffects)) {
                const weatherTypeId = weatherMap.get(weatherTr);
                if (!weatherTypeId) {
                    console.warn(`[Falukant] Wettertyp "${weatherTr}" nicht gefunden, überspringe`);
                    continue;
                }

                effectEntries.push({
                    productId,
                    weatherTypeId,
                    qualityEffect: effectValue
                });
            }
        }

        // Bulk insert mit ignoreDuplicates
        await ProductWeatherEffect.bulkCreate(effectEntries, {
            ignoreDuplicates: true
        });

        console.log(`[Falukant] Produkt-Wetter-Effekte initialisiert: ${effectEntries.length} Einträge`);
    } catch (error) {
        console.error('❌ Fehler beim Initialisieren der Produkt-Wetter-Effekte:', error);
        throw error;
    }
};
