local UEHelpers = require("UEHelpers")
local Config = require("config")

local MOD_NAME = "Subnautica2ComfortTweaks"

local enabled = Config.Enabled ~= false
local lastAppliedFOV = nil

local function Log(message)
    if Config.Debug then
        print(string.format("[%s] %s\n", MOD_NAME, message))
    end
end

local function IsValidObject(obj)
    if obj == nil then
        return false
    end

    local ok, isValid = pcall(function()
        return obj.IsValid ~= nil and obj:IsValid()
    end)

    return ok and isValid == true
end

local function GetPlayerController()
    local ok, pc = pcall(function()
        return UEHelpers:GetPlayerController()
    end)

    if ok and IsValidObject(pc) then
        return pc
    end

    return nil
end

local function TryCallPlayerControllerFOV(pc, fov)
    if not IsValidObject(pc) then
        return false
    end

    local ok = pcall(function()
        pc:FOV(fov)
    end)

    if ok then
        Log(string.format("Called PlayerController:FOV(%.1f)", fov))
        return true
    end

    return false
end

local function ApplyFOV(fovOverride, force)
    if not enabled and not force then
        return
    end

    local fov = tonumber(fovOverride or Config.TargetFOV) or 95.0
    local pc = GetPlayerController()

    Log(string.format("ApplyFOV start: requested=%.1f enabled=%s force=%s lastApplied=%s", fov, tostring(enabled),
        tostring(force == true), tostring(lastAppliedFOV)))

    local changed = false
    changed = TryCallPlayerControllerFOV(pc, fov)

    if changed then
        lastAppliedFOV = fov
    else
        Log("Could not apply FOV; player camera not ready")
    end
end

local function ApplyAll()
    ExecuteInGameThread(function()
        ApplyFOV(nil, false)
    end)
end

local function ApplyResetFOV()
    ExecuteInGameThread(function()
        ApplyFOV(tonumber(Config.ResetFOVOnDisable) or 90.0, true)
    end)
end

print(string.format("[%s] Loaded\n", MOD_NAME))

-- ExecuteWithDelay(3000, ApplyAll)

NotifyOnNewObject("/Script/Engine.PlayerCameraManager", function(obj)
    ExecuteWithDelay(500, ApplyAll)
end)

if Config.EnableToggleHotkey then
    RegisterKeyBind(Key.F7, function()
        enabled = not enabled
        Log("Enabled = " .. tostring(enabled))

        if enabled then
            ApplyAll()
        else
            ApplyResetFOV()
        end
    end)
end
