local Event = require("ui/event")
local InfoMessage = require("ui/widget/infomessage")
local UIManager = require("ui/uimanager")
local logger = require("logger")
local util = require("util")
local sha2 = require("ffi/sha2")
local _ = require("readest_i18n")

local SyncConfig = {}

-- Readest md5s the NFC-normalized hash source (book.ts getMetadataHashInfo);
-- utf8proc ships with KOReader but not with the spec harness, so fall back
-- to identity when it is unavailable.
local ok_utf8proc, Utf8Proc = pcall(require, "ffi/utf8proc")
local normalize_nfc = (ok_utf8proc and type(Utf8Proc.normalize_NFC) == "function")
    and Utf8Proc.normalize_NFC
    or function(s) return s end

local function normalizeIdentifier(identifier)
    if identifier:match("urn:") then
        return identifier:match("([^:]+)$")
    elseif identifier:match(":") then
        return identifier:match("^[^:]+:(.+)$")
    end
    return identifier
end

local function normalizeAuthor(author)
    author = author:gsub("^%s*(.-)%s*$", "%1")
    return author
end

-- Builds the cross-device book fingerprint from sidecar metadata. MUST stay
-- consistent with getMetadataHashInfo in apps/readest-app/src/utils/book.ts:
-- the md5 of hash_source is the identity that book rows, configs and notes
-- sync under, so any divergence forks a book's progress across devices.
function SyncConfig:computeMetadataHashInfo(doc_props, doc_path)
    doc_props = doc_props or {}
    local _dir, filename = util.splitFilePathName(doc_path or '')
    local basename, suffix = util.splitFileNameSuffix(filename)

    local title = doc_props.title or ''
    if title == '' then
        title = basename or ''
    end

    local authors_raw = doc_props.authors or ''
    local authors_list = {}
    if authors_raw:find("\n") then
        local list = util.splitToArray(authors_raw, "\n")
        for i, author in ipairs(list) do
            authors_list[i] = normalizeAuthor(author)
        end
    elseif authors_raw ~= '' then
        authors_list = { normalizeAuthor(authors_raw) }
    end

    local identifiers_raw = doc_props.identifiers or ''
    local identifiers_list = {}
    if identifiers_raw:find("\n") then
        local list = util.splitToArray(identifiers_raw, "\n")
        local normalized = {}
        for i, id in ipairs(list) do
            normalized[i] = normalizeIdentifier(id)
        end
        -- Scheme priority mirrors Readest's getPreferredIdentifier: uuid
        -- beats calibre beats isbn, regardless of listing order.
        local preferred = nil
        for _, scheme in ipairs({ "uuid", "calibre", "isbn" }) do
            for i, id in ipairs(list) do
                if id:lower():find(scheme, 1, true) then
                    preferred = normalized[i]
                    break
                end
            end
            if preferred then break end
        end
        if preferred then
            identifiers_list = { preferred }
        else
            identifiers_list = normalized
        end
    elseif identifiers_raw ~= '' then
        identifiers_list = { normalizeIdentifier(identifiers_raw) }
    end

    local hash_source = title .. "|" .. table.concat(authors_list, ",") .. "|" .. table.concat(identifiers_list, ",")
    -- PDF metadata is often generic boilerplate (every PowerPoint export is
    -- titled "PowerPoint Presentation"), so Readest salts PDF hashes with the
    -- import filename (issue #5411). Salt with ours the same way.
    if suffix and suffix:lower() == "pdf" then
        hash_source = hash_source .. "|" .. basename
    end
    return {
        title = title,
        authors = authors_list,
        identifiers = identifiers_list,
        hash_source = hash_source,
        meta_hash = sha2.md5(normalize_nfc(hash_source)),
    }
end

function SyncConfig:getMetadataHashInfo(ui)
    return self:computeMetadataHashInfo(
        ui.doc_settings:readSetting("doc_props"),
        ui.doc_settings:readSetting("doc_path")
    )
end

function SyncConfig:generateMetadataHash(ui)
    return self:getMetadataHashInfo(ui).meta_hash
end

function SyncConfig:getMetaHash(ui, store)
    local doc_readest_sync = ui.doc_settings:readSetting("readest_sync") or {}
    -- The value stamped when the book first entered the fleet is the
    -- authoritative one: Readest never recomputes a PDF's metaHash after
    -- import (the filename salt is unrecoverable there), so a synced library
    -- row must beat anything computed or cached locally.
    local meta_hash
    if store then
        local book_hash = self:getDocumentIdentifier(ui)
        local row = book_hash and store:_getRowRaw(book_hash)
        if row and row.meta_hash and row.meta_hash ~= "" then
            meta_hash = row.meta_hash
        end
    end
    meta_hash = meta_hash or doc_readest_sync.meta_hash_v1
    if not meta_hash then
        meta_hash = self:generateMetadataHash(ui)
    end
    -- Annotation flows read meta_hash_v1 straight from the sidecar, so the
    -- resolved value must land there whichever branch produced it.
    if meta_hash and doc_readest_sync.meta_hash_v1 ~= meta_hash then
        doc_readest_sync.meta_hash_v1 = meta_hash
        ui.doc_settings:saveSetting("readest_sync", doc_readest_sync)
    end
    return meta_hash
end

function SyncConfig:getDocumentIdentifier(ui)
    return ui.doc_settings:readSetting("partial_md5_checksum")
end

function SyncConfig:getCurrentBookConfig(ui)
    local book_hash = self:getDocumentIdentifier(ui)
    local meta_hash = self:getMetaHash(ui)
    if not book_hash or not meta_hash then
        UIManager:show(InfoMessage:new{
            text = _("Cannot identify the current book"),
            timeout = 2,
        })
        return nil
    end

    local config = {
        bookHash = book_hash,
        metaHash = meta_hash,
        progress = "",
        xpointer = "",
        updatedAt = os.time() * 1000,
    }

    local current_page = ui:getCurrentPage()
    local page_count = ui.document:getPageCount()
    config.progress = {current_page, page_count}

    if not ui.document.info.has_pages then
        config.xpointer = ui.rolling:getLastProgress()
    end

    return config
end

function SyncConfig:applyBookConfig(ui, config)
    logger.dbg("ReadestSync: Applying book config:", config)
    local xpointer = config.xpointer
    local progress = config.progress
    local has_pages = ui.document.info.has_pages
    local progress_pattern = "^%[(%d+),(%d+)%]$"
    if has_pages and progress then
        local page, _total_pages = progress:match(progress_pattern)
        local current_page = ui:getCurrentPage()
        local new_page = tonumber(page)
        if new_page > current_page then
            ui.link:addCurrentLocationToStack()
            ui:handleEvent(Event:new("GotoPage", new_page))
            self:showSyncedMessage()
        end
    end
    if not has_pages and xpointer then
        local last_xpointer = ui.rolling:getLastProgress()
        local working_xpointer = xpointer
        local cmp_result = ui.document:compareXPointers(last_xpointer, working_xpointer)
        while cmp_result == nil and working_xpointer do
            local last_slash_pos = working_xpointer:match("^.*()/")
            if last_slash_pos and last_slash_pos > 1 then
                working_xpointer = working_xpointer:sub(1, last_slash_pos - 1)
                cmp_result = ui.document:compareXPointers(last_xpointer, working_xpointer)
            else
                break
            end
        end
        if cmp_result > 0 then
            ui.link:addCurrentLocationToStack()
            ui:handleEvent(Event:new("GotoXPointer", working_xpointer))
            self:showSyncedMessage()
        end
    end
end

function SyncConfig:showSyncedMessage()
    UIManager:show(InfoMessage:new{
        text = _("Progress has been synchronized."),
        timeout = 3,
    })
end

function SyncConfig:push(ui, settings, client, interactive, last_sync_timestamp)
    local config = self:getCurrentBookConfig(ui)
    if not config then return last_sync_timestamp end

    if interactive then
        UIManager:show(InfoMessage:new{
            text = _("Pushing reading progress..."),
            timeout = 1,
        })
    end

    local payload = {
        books = {},
        notes = {},
        configs = { config },
    }

    client:pushChanges(
        payload,
        function(success, _response)
            if interactive then
                if success then
                    UIManager:show(InfoMessage:new{
                        text = _("Reading progress pushed successfully"),
                        timeout = 2,
                    })
                else
                    UIManager:show(InfoMessage:new{
                        text = _("Failed to push reading progress"),
                        timeout = 2,
                    })
                end
            end
            if success and ui.doc_settings then
                local doc_readest_sync = ui.doc_settings:readSetting("readest_sync") or {}
                doc_readest_sync.last_synced_at_config = os.time()
                ui.doc_settings:saveSetting("readest_sync", doc_readest_sync)
            end
        end
    )

    if not interactive then
        return os.time()
    end
    return last_sync_timestamp
end

function SyncConfig:pull(ui, settings, client, book_hash, meta_hash, interactive, logout_fn)
    if interactive then
        UIManager:show(InfoMessage:new{
            text = _("Pulling reading progress..."),
            timeout = 1,
        })
    end

    client:pullChanges(
        {
            since = 0,
            type = "configs",
            book = book_hash,
            meta_hash = meta_hash,
        },
        function(success, response, status)
            if not success then
                -- Auth failure: server returns HTTP 403 with body
                -- {error="Not authenticated"} per apps/readest-app/src/pages/api/sync.ts:31.
                -- Check the status code primarily so future endpoints with
                -- different body shapes still trigger relogin (codex finding).
                local is_auth_fail = status == 401 or status == 403
                    or (response and response.error == "Not authenticated")
                if is_auth_fail then
                    if interactive then
                        UIManager:show(InfoMessage:new{
                            text = _("Authentication failed, please login again"),
                            timeout = 2,
                        })
                    end
                    if logout_fn then logout_fn() end
                    return
                end
                if interactive then
                    UIManager:show(InfoMessage:new{
                        text = _("Failed to pull reading progress"),
                        timeout = 2,
                    })
                end
                return
            end

            if ui.doc_settings then
                local doc_readest_sync = ui.doc_settings:readSetting("readest_sync") or {}
                doc_readest_sync.last_synced_at_config = os.time()
                ui.doc_settings:saveSetting("readest_sync", doc_readest_sync)
            end

            local data = response.configs
            if data and #data > 0 then
                local config = data[1]
                if config then
                    self:applyBookConfig(ui, config)
                    if interactive then
                        UIManager:show(InfoMessage:new{
                            text = _("Reading progress synchronized"),
                            timeout = 2,
                        })
                    end
                    return
                end
            end

            if interactive then
                UIManager:show(InfoMessage:new{
                    text = _("No saved reading progress found for this book"),
                    timeout = 2,
                })
            end
        end
    )
end

return SyncConfig
