// Client-side scoring library — mirrors sidecar computation for live preview

export type TaskWeightConfig = {
    weight: number;
    slaMinutes: number;
    enabled: boolean;
};

export type PriorityConfig = {
    taskWeights: Record<string, TaskWeightConfig>;
    campaignWeights: Record<string, number>;
    sourceWeights: Record<string, number>;
};

export type ScoreResult = {
    score: number;
    baseScore: number;
    slaMultiplier: number;
    campaignMultiplier: number;
    slaElapsedPercent: number;
    slaStatus: 'low' | 'medium' | 'high' | 'critical';
    taskType: string;
};

export function computeSlaMultiplier(slaElapsedPercent: number): number {
    const elapsed = slaElapsedPercent / 100;
    if (elapsed > 1) return 1.0 + (elapsed - 1) * 0.5;
    return Math.pow(elapsed, 1.6);
}

export function computeSlaStatus(slaElapsedPercent: number): 'low' | 'medium' | 'high' | 'critical' {
    if (slaElapsedPercent > 100) return 'critical';
    if (slaElapsedPercent >= 80) return 'high';
    if (slaElapsedPercent >= 50) return 'medium';
    return 'low';
}

export function inferTaskType(item: any): string {
    if (item.callStatus === 'MISSED' || item.type === 'missed') return 'missed_call';
    if (item.followUpType === 'CALLBACK' || item.type === 'callback' || item.type === 'follow-up') return 'follow_up';
    if (item.contactAttempts >= 3) return 'attempt_3';
    if (item.contactAttempts >= 2) return 'attempt_2';
    return 'campaign_lead';
}

export function scoreItem(item: any, config: PriorityConfig): ScoreResult {
    const taskType = inferTaskType(item);
    const taskConfig = config.taskWeights[taskType];

    if (!taskConfig?.enabled) {
        return { score: 0, baseScore: 0, slaMultiplier: 1, campaignMultiplier: 1, slaElapsedPercent: 0, slaStatus: 'low', taskType };
    }

    const createdAt = item.createdAt ? new Date(item.createdAt).getTime() : Date.now();
    const elapsedMinutes = (Date.now() - createdAt) / 60000;
    const slaElapsedPercent = Math.round((elapsedMinutes / taskConfig.slaMinutes) * 100);

    const baseScore = taskConfig.weight;
    const slaMultiplier = computeSlaMultiplier(slaElapsedPercent);

    let campaignMultiplier = 1;
    if (item.campaignId && config.campaignWeights[item.campaignId]) {
        const cw = (config.campaignWeights[item.campaignId] ?? 5) / 10;
        const source = item.leadSource ?? item.source ?? 'OTHER';
        const sw = (config.sourceWeights[source] ?? 5) / 10;
        campaignMultiplier = cw * sw;
    }

    const score = Math.round(baseScore * slaMultiplier * campaignMultiplier * 100) / 100;

    return {
        score,
        baseScore,
        slaMultiplier: Math.round(slaMultiplier * 100) / 100,
        campaignMultiplier: Math.round(campaignMultiplier * 100) / 100,
        slaElapsedPercent,
        slaStatus: computeSlaStatus(slaElapsedPercent),
        taskType,
    };
}

export function scoreAndRankItems(items: any[], config: PriorityConfig): (any & ScoreResult)[] {
    return items
        .map(item => ({ ...item, ...scoreItem(item, config) }))
        .sort((a, b) => b.score - a.score);
}

export const TASK_TYPE_LABELS: Record<string, string> = {
    missed_call: 'Missed Calls',
    follow_up: 'Follow-ups',
    campaign_lead: 'Campaign Leads',
    attempt_2: '2nd Attempt',
    attempt_3: '3rd Attempt',
};

export const SOURCE_LABELS: Record<string, string> = {
    WHATSAPP: 'WhatsApp',
    PHONE: 'Phone',
    FACEBOOK_AD: 'Facebook Ad',
    GOOGLE_AD: 'Google Ad',
    INSTAGRAM: 'Instagram',
    WEBSITE: 'Website',
    REFERRAL: 'Referral',
    WALK_IN: 'Walk-in',
    OTHER: 'Other',
};

export const DEFAULT_PRIORITY_CONFIG: PriorityConfig = {
    taskWeights: {
        missed_call: { weight: 9, slaMinutes: 720, enabled: true },
        follow_up: { weight: 8, slaMinutes: 1440, enabled: true },
        campaign_lead: { weight: 7, slaMinutes: 2880, enabled: true },
        attempt_2: { weight: 6, slaMinutes: 1440, enabled: true },
        attempt_3: { weight: 4, slaMinutes: 2880, enabled: true },
    },
    campaignWeights: {},
    sourceWeights: {
        WHATSAPP: 9,
        PHONE: 8,
        FACEBOOK_AD: 7,
        GOOGLE_AD: 7,
        INSTAGRAM: 5,
        WEBSITE: 7,
        REFERRAL: 6,
        WALK_IN: 5,
        OTHER: 5,
    },
};
