import { ConnectionOpinionService } from "../../connections/services/ConnectionOpinionService.js";
import { ConnectionStore } from "../../connections/services/ConnectionStore.js";
import { ConnectionTargetResolver } from "../../connections/services/ConnectionTargetResolver.js";

export class FactionDiplomacyViewModel {
    static fromEntity(entity = {}) {
        const target = ConnectionTargetResolver.fromCampaignEntity(entity);
        const factionNodeId = ConnectionTargetResolver.getNodeId(target);
        if (!target || !factionNodeId) return this.#empty();

        const relations = ConnectionStore.getConnectionsForNode(factionNodeId)
            .filter(({ node }) => node.kind === "nexus-entity" && node.entityType === "faction")
            .map(({ edge, node }) => this.#relation(edge, node, factionNodeId))
            .filter(Boolean)
            .sort((left, right) => left.sort - right.sort || left.name.localeCompare(right.name));

        return {
            relations,
            hasRelations: relations.length > 0,
            count: relations.length
        };
    }

    static #relation(edge, node, factionNodeId) {
        const faction = ConnectionTargetResolver.resolveDisplayNodeSync(node);
        if (!edge || !faction || faction.missing) return null;

        const view = ConnectionStore.getConnectionView(edge, factionNodeId);
        const reciprocalView = ConnectionStore.getConnectionView(edge, node.id);
        const opinion = this.#opinion(edge, factionNodeId);
        const reciprocalOpinion = this.#opinion(edge, node.id);
        const relationshipLabel = String(view.role || "Diplomatic Contact").trim();
        const reciprocalLabel = String(reciprocalView.role || "").trim();

        return {
            edgeId: edge.id,
            nodeId: node.id,
            name: faction.name || "Unknown Organization",
            imageSrc: faction.img || "",
            subtitle: faction.subtitle || "Organization",
            relationshipLabel,
            reciprocalLabel: reciprocalLabel && reciprocalLabel !== relationshipLabel ? reciprocalLabel : "",
            note: String(view.note || "").trim(),
            sort: Number(view.sort || 100),
            opinion,
            reciprocalOpinion,
            hasReciprocalOpinion: !!reciprocalOpinion
        };
    }

    static #opinion(edge, observerNodeId) {
        const opinion = ConnectionOpinionService.resolvePerspective(edge, observerNodeId);
        if (!opinion) return null;
        return {
            score: Number(opinion.score || 0),
            scoreLabel: opinion.scoreLabel,
            tierLabel: opinion.tier.label,
            tierColor: opinion.tier.color
        };
    }

    static #empty() {
        return { relations: [], hasRelations: false, count: 0 };
    }
}
