package connector

import (
	"context"
	"fmt"
	"net/http"
	"strings"
	"time"

	"maunium.net/go/mautrix/bridgev2"
	bridgev2matrix "maunium.net/go/mautrix/bridgev2/matrix"
	"maunium.net/go/mautrix/event"
	"maunium.net/go/mautrix/id"
)

// refreshGhostAvatars re-uploads the avatar for every ghost that is a member of
// any of this login's portal rooms.
//
// Why this exists:
// bridgev2 only calls NetworkAPI.GetUserInfo() for a ghost
//   - when the ghost has no name/avatar yet (Ghost.UpdateInfoIfNecessary), or
//   - when a remote event arrives for that ghost.
// So after the avatar algorithm in avatar.go changes (new candidate sources,
// ICO->PNG conversion, ...), already-known ghosts keep whatever was uploaded
// months ago and a plain bridge restart does not fix them. mautrix-whatsapp
// solves the same problem with its `!wa sync contacts` command.
//
// The member list is used instead of PortalMetadata.LastSender because that
// field only ever holds the *most recent* sender: every older sender would keep
// its stale avatar forever.
//
// This runs once on connect, is deliberately sequential and never fails hard:
// it must not delay or break mail polling.
func (c *MailClient) refreshGhostAvatars(ctx context.Context) {
	if c.Connector == nil || c.Connector.Bridge == nil {
		return
	}
	portals, err := c.Connector.Bridge.GetAllPortals(ctx)
	if err != nil {
		c.Log.Warn().Err(err).Msg("avatar refresh: failed to list portals")
		return
	}

	seen := make(map[id.UserID]bool)
	var wanted []id.UserID
	add := func(mxid id.UserID) {
		if mxid == "" || seen[mxid] {
			return
		}
		seen[mxid] = true
		wanted = append(wanted, mxid)
	}

	// Also cover portals that have no Matrix room yet (never messaged into).
	var extraIDs []string
	for _, portal := range portals {
		if portal.Receiver != c.Login.ID {
			continue
		}
		if portal.MXID != "" {
			members, err := c.Connector.Bridge.Matrix.GetMembers(ctx, portal.MXID)
			if err != nil {
				c.Log.Debug().Err(err).Str("room", string(portal.MXID)).
					Msg("avatar refresh: failed to get room members")
			}
			for mxid := range members {
				if c.Connector.Bridge.IsGhostMXID(mxid) {
					add(mxid)
				}
			}
		}
		extraIDs = append(extraIDs, string(portal.ID))
		if meta, ok := portal.Metadata.(*PortalMetadata); ok && meta != nil && meta.LastSender != "" {
			extraIDs = append(extraIDs, meta.LastSender)
		}
	}

	updated, unchanged, failed := 0, 0, 0
	repaired := 0
	handle := func(gctx context.Context, ghost *bridgev2.Ghost) {
		if c.repairPoisonedAvatarCache(gctx, ghost) {
			repaired++
		}
		before := string(ghost.AvatarID) + "|" + string(ghost.AvatarMXC)
		info, err := c.GetUserInfo(gctx, ghost)
		if err != nil || info == nil {
			failed++
			return
		}
		ghost.UpdateInfo(gctx, info)
		if before != string(ghost.AvatarID)+"|"+string(ghost.AvatarMXC) {
			updated++
		} else {
			unchanged++
		}
	}

	for _, mxid := range wanted {
		if ctx.Err() != nil {
			return
		}
		ghost, err := c.Connector.Bridge.GetGhostByMXID(ctx, mxid)
		if err != nil || ghost == nil {
			failed++
			continue
		}
		// Fresh budget per ghost: one dead domain must not eat the whole run.
		// The avatar Get() closure carries its own 25s cap anyway.
		gctx, cancel := context.WithTimeout(ctx, 45*time.Second)
		handle(gctx, ghost)
		cancel()
		select {
		case <-ctx.Done():
			return
		case <-time.After(120 * time.Millisecond):
		}
	}
	// Domain ghosts (the portal ID itself, e.g. "user.luma-mail.com") have no
	// Matrix room membership, so they are handled separately.
	for _, raw := range extraIDs {
		if ctx.Err() != nil {
			return
		}
		addr := strings.TrimSpace(strings.ToLower(raw))
		if addr == "" {
			continue
		}
		ghost, err := c.Connector.Bridge.GetGhostByID(ctx, ghostIDForEmail(addr))
		if err != nil || ghost == nil {
			continue
		}
		gctx, cancel := context.WithTimeout(ctx, 45*time.Second)
		handle(gctx, ghost)
		cancel()
	}

	// The mail bridge only ever set *profile* avatars on ghosts. Element's room
	// list shows m.room.avatar though, so the mail rooms looked empty even
	// though every sender had a perfectly good domain logo. Set the room avatar
	// as the bridge bot (it owns these rooms, PL 9001; the Matrix user has PL 0
	// because bridgev2's PowerLevelOverride only lists the bot).
	roomsSet := 0
	botIntent := c.Connector.Bridge.Matrix.BotIntent()
	avatarContent := func(mxc id.ContentURIString) *event.Content {
		return &event.Content{
			Parsed: &event.RoomAvatarEventContent{URL: mxc},
		}
	}
	for _, portal := range portals {
		if ctx.Err() != nil {
			return
		}
		if portal.Receiver != c.Login.ID || portal.MXID == "" {
			continue
		}
		ghost, err := c.Connector.Bridge.GetGhostByID(ctx, ghostIDForEmail(string(portal.ID)))
		if err != nil || ghost == nil || ghost.AvatarMXC == "" {
			continue
		}
		if portal.AvatarMXC == ghost.AvatarMXC {
			continue
		}
		if _, err := botIntent.SendState(ctx, portal.MXID, event.StateRoomAvatar, "", avatarContent(ghost.AvatarMXC), time.Time{}); err != nil {
			c.Log.Debug().Err(err).Str("room", string(portal.MXID)).Msg("avatar refresh: failed to set room avatar")
			continue
		}
		roomsSet++
	}

	c.Log.Info().
		Int("checked", updated+unchanged).
		Int("updated", updated).
		Int("unchanged", unchanged).
		Int("failed", failed).
		Int("repaired", repaired).
		Int("room_avatars_set", roomsSet).
		Msg("avatar refresh finished")
}

// repairPoisonedAvatarCache compares what the bridge database *claims* it
// uploaded against what the homeserver actually serves for that ghost's
// profile, and wipes bridgev2's avatar cache when the two disagree.
//
// Why this is needed (observed 2026-09-30, all 110 mail ghosts affected):
// bridgev2 caches the avatar decision in three columns - avatar_id, avatar_hash
// and avatar_set. ghost.go:173 then short-circuits
//
//	if ghost.AvatarID == avatar.ID && (avatar.Remove || ghost.AvatarMXC != "") && ghost.AvatarSet {
//	    return false, false
//	}
//
// and even if it did not, Reupload() at ghost.go:129 short-circuits with
//
//	if hash == currentHash && currentMXC != "" { return currentMXC, hash, nil }
//
// Neither path ever talks to the homeserver. So a single bogus avatar_mxc is
// permanent: every refresh logs "unchanged", no upload happens, and
// refreshGhostAvatars' room-avatar loop (which reuses ghost.AvatarMXC verbatim
// for m.room.avatar) republishes the dead URI into every mail portal room.
// Clients then render a broken image.
//
// The authoritative source is the homeserver's own profile. Wiping
// avatar_id/avatar_hash/avatar_mxc/avatar_set forces prepareAvatar to take the
// real upload path, and the new content URI is then written back to both the
// profile and the room.
func (c *MailClient) repairPoisonedAvatarCache(ctx context.Context, ghost *bridgev2.Ghost) bool {
	if c.Connector == nil || c.Connector.Bridge == nil || ghost == nil {
		return false
	}
	// Only ghosts that believe they are fully uploaded are interesting.
	if !ghost.AvatarSet || ghost.AvatarMXC == "" {
		return false
	}
	mxid := c.Connector.Bridge.Matrix.FormatGhostMXID(ghost.ID)
	if mxid == "" {
		return false
	}
	botIntent, ok := c.Connector.Bridge.Matrix.BotIntent().(*bridgev2matrix.ASIntent)
	if !ok || botIntent == nil || botIntent.Matrix == nil {
		c.Log.Error().Str("intent_type", fmt.Sprintf("%T", c.Connector.Bridge.Matrix.BotIntent())).
			Msg("avatar cache check: bot intent is not a *matrix.ASIntent, cannot verify")
		return false
	}
	uri, err := id.ParseContentURI(string(ghost.AvatarMXC))
	if err != nil || uri.IsEmpty() {
		c.Log.Warn().
			Str("mxid", string(mxid)).
			Str("cached", string(ghost.AvatarMXC)).
			Msg("avatar cache holds an unparseable content URI, forcing re-upload")
		ghost.AvatarID = ""
		ghost.AvatarHash = [32]byte{}
		ghost.AvatarMXC = ""
		ghost.AvatarSet = false
		return true
	}
	// The single most reliable check: does the homeserver still have the bytes?
	// This catches the failure mode where the profile event exists but the
	// upload was never completed (or was purged), which is exactly what
	// happened to all 110 mail ghosts on 2026-09-30. Note that comparing against
	// the profile event is NOT enough: the homeserver happily stores an mxc URI
	// it cannot serve.
	resp, err := botIntent.Matrix.Download(ctx, uri)
	if resp != nil && resp.Body != nil {
		_ = resp.Body.Close()
	}
	if err == nil && resp != nil && resp.StatusCode == http.StatusOK {
		return false
	}
	status := 0
	if resp != nil {
		status = resp.StatusCode
	}
	c.Log.Warn().
		Str("mxid", string(mxid)).
		Str("cached", string(ghost.AvatarMXC)).
		Int("status", status).
		Err(err).
		Msg("homeserver cannot serve the cached avatar, forcing re-upload")
	ghost.AvatarID = ""
	ghost.AvatarHash = [32]byte{}
	ghost.AvatarMXC = ""
	ghost.AvatarSet = false
	return true
}
