/**
 * Rule Engine — Pure evaluation functions (no DB calls, fully testable)
 *
 * Evaluates transition rule conditions against a candidate context object.
 * Supports: min_score, feedback_count, interview_completed, min_time_in_stage,
 * has_notes, has_documents, approval_required, stage_type_match, tag_required.
 */

// ─── Types ──────────────────────────────────────────────
export interface RuleCondition {
    field: string;       // e.g. "min_score", "feedback_count"
    operator: string;    // e.g. "gte", "eq", "exists", "contains"
    value: string | number | boolean;    // e.g. 70, 3, true, "background_check"
}

export interface RuleAction {
    type: string;        // e.g. "block", "notify", "auto_move", "show_message"
    params?: Record<string, any>;
}

export interface TransitionRuleDef {
    id: string;
    name: string;
    description?: string | null;
    rule_type: string;
    conditions: RuleCondition[];
    actions?: RuleAction[] | null;
    allow_override: boolean;
    override_roles: string[];
    priority: number;
}

export interface CandidateContext {
    overallScore: number | null;
    technicalScore: number | null;
    feedbackCount: number;
    positiveFeedbackCount: number;
    interviewCount: number;
    completedInterviewCount: number;
    noteCount: number;
    hoursInCurrentStage: number;
    tags: string[];
    hasResumeUploaded: boolean;
    hasOffer: boolean;
    offerStatus: string | null;
    applicationStatus: string;
    rating: number | null;
    teamApprovals: { role: string; approved: boolean }[];
}

export interface RuleViolation {
    ruleId: string;
    ruleName: string;
    description: string | null | undefined;
    condition: RuleCondition;
    message: string;
    allowOverride: boolean;
    overrideRoles: string[];
}

export interface EvaluationResult {
    allowed: boolean;
    violations: RuleViolation[];
    warnings: string[];
    autoActions: RuleAction[];
}

// ─── Condition Evaluators ───────────────────────────────
const evaluators: Record<string, (condition: RuleCondition, ctx: CandidateContext) => { met: boolean; message: string }> = {
    min_score: (c, ctx) => {
        const score = ctx.overallScore ?? 0;
        const met = score >= Number(c.value);
        return { met, message: met ? "" : `Overall score (${Math.round(score)}) is below minimum requirement (${c.value})` };
    },

    min_technical_score: (c, ctx) => {
        const score = ctx.technicalScore ?? 0;
        const met = score >= Number(c.value);
        return { met, message: met ? "" : `Technical score (${Math.round(score)}) is below minimum (${c.value})` };
    },

    feedback_count: (c, ctx) => {
        const met = ctx.feedbackCount >= Number(c.value);
        return { met, message: met ? "" : `Requires ${c.value} feedback submissions. Currently have ${ctx.feedbackCount}` };
    },

    positive_feedback_count: (c, ctx) => {
        const met = ctx.positiveFeedbackCount >= Number(c.value);
        return { met, message: met ? "" : `Requires ${c.value} positive feedback. Currently have ${ctx.positiveFeedbackCount}` };
    },

    interview_completed: (c, ctx) => {
        const met = ctx.completedInterviewCount >= Number(c.value || 1);
        return { met, message: met ? "" : `Requires ${c.value || 1} completed interview(s). Currently have ${ctx.completedInterviewCount}` };
    },

    min_time_in_stage: (c, ctx) => {
        const minHours = Number(c.value);
        const met = ctx.hoursInCurrentStage >= minHours;
        const remaining = Math.max(0, minHours - ctx.hoursInCurrentStage);
        return { met, message: met ? "" : `Candidate must remain in current stage for at least ${minHours} hours. ${Math.round(remaining)} hours remaining` };
    },

    has_notes: (c, ctx) => {
        const min = Number(c.value || 1);
        const met = ctx.noteCount >= min;
        return { met, message: met ? "" : `Requires at least ${min} note(s). Currently have ${ctx.noteCount}` };
    },

    has_rating: (c, ctx) => {
        const minRating = Number(c.value || 1);
        const met = (ctx.rating ?? 0) >= minRating;
        return { met, message: met ? "" : `Requires rating of ${minRating}+. Current: ${ctx.rating ?? "No rating"}` };
    },

    tag_required: (c, ctx) => {
        const tag = String(c.value).toLowerCase();
        const met = ctx.tags.some(t => t.toLowerCase() === tag);
        return { met, message: met ? "" : `Requires tag "${c.value}"` };
    },

    approval_required: (c, ctx) => {
        const role = String(c.value);
        const approval = ctx.teamApprovals.find(a => a.role === role);
        const met = approval?.approved === true;
        return { met, message: met ? "" : `Requires approval from ${role.replace(/_/g, " ")}` };
    },

    has_offer: (c, ctx) => {
        const met = ctx.hasOffer;
        return { met, message: met ? "" : "Requires an offer to be created first" };
    },

    offer_status: (c, ctx) => {
        const expectedStatus = String(c.value);
        const met = ctx.offerStatus === expectedStatus;
        return { met, message: met ? "" : `Offer must be in "${expectedStatus}" status. Current: "${ctx.offerStatus || "none"}"` };
    },
};

// ─── Core Evaluation ────────────────────────────────────

/**
 * Evaluate a single condition against the candidate context.
 */
export function evaluateCondition(condition: RuleCondition, ctx: CandidateContext): { met: boolean; message: string } {
    const evaluator = evaluators[condition.field];
    if (!evaluator) {
        // Unknown condition type — treat as met (don't block on unknown rules)
        return { met: true, message: "" };
    }
    return evaluator(condition, ctx);
}

/**
 * Evaluate all rules applicable to a transition.
 * Returns whether the transition is allowed and any violations.
 */
export function evaluateRuleSet(rules: TransitionRuleDef[], ctx: CandidateContext): EvaluationResult {
    const violations: RuleViolation[] = [];
    const warnings: string[] = [];
    const autoActions: RuleAction[] = [];

    // Sort by priority (higher first)
    const sorted = [...rules].sort((a, b) => b.priority - a.priority);

    for (const rule of sorted) {
        if (rule.rule_type === "requirement") {
            // All conditions must be met
            const conditions = rule.conditions as RuleCondition[];
            for (const condition of conditions) {
                const result = evaluateCondition(condition, ctx);
                if (!result.met) {
                    violations.push({
                        ruleId: rule.id,
                        ruleName: rule.name,
                        description: rule.description,
                        condition,
                        message: result.message,
                        allowOverride: rule.allow_override,
                        overrideRoles: rule.override_roles,
                    });
                }
            }
        } else if (rule.rule_type === "validation") {
            // Validation Rules — same as requirement but with warnings instead of blocks
            const conditions = rule.conditions as RuleCondition[];
            for (const condition of conditions) {
                const result = evaluateCondition(condition, ctx);
                if (!result.met) {
                    warnings.push(`⚠️ ${rule.name}: ${result.message}`);
                }
            }
        } else if (rule.rule_type === "auto_transition") {
            // Check if auto-transition conditions are met
            const conditions = rule.conditions as RuleCondition[];
            const allMet = conditions.every(c => evaluateCondition(c, ctx).met);
            if (allMet && rule.actions) {
                autoActions.push(...(rule.actions as RuleAction[]));
            }
        } else if (rule.rule_type === "notification") {
            // Notification rules always pass through, just collect actions
            const conditions = rule.conditions as RuleCondition[];
            const allMet = conditions.every(c => evaluateCondition(c, ctx).met);
            if (allMet && rule.actions) {
                autoActions.push(...(rule.actions as RuleAction[]));
            }
        }
    }

    return {
        allowed: violations.length === 0,
        violations,
        warnings,
        autoActions,
    };
}

// ─── Rule Templates ─────────────────────────────────────
export const RULE_TEMPLATES: Omit<TransitionRuleDef, "id">[] = [
    {
        name: "Minimum Score Requirement",
        description: "Blocks transition unless candidate has minimum overall score",
        rule_type: "requirement",
        conditions: [{ field: "min_score", operator: "gte", value: 70 }],
        actions: null,
        allow_override: true,
        override_roles: ["hiring_manager", "hr_admin"],
        priority: 10,
    },
    {
        name: "Interview Feedback Required",
        description: "Requires at least 1 completed interview with feedback before advancing",
        rule_type: "requirement",
        conditions: [
            { field: "interview_completed", operator: "gte", value: 1 },
            { field: "feedback_count", operator: "gte", value: 1 },
        ],
        actions: null,
        allow_override: true,
        override_roles: ["hiring_manager", "hr_admin"],
        priority: 8,
    },
    {
        name: "Multiple Feedback Required",
        description: "Requires at least 3 positive feedback submissions before advancing to offer",
        rule_type: "requirement",
        conditions: [{ field: "positive_feedback_count", operator: "gte", value: 3 }],
        actions: null,
        allow_override: true,
        override_roles: ["hiring_manager"],
        priority: 9,
    },
    {
        name: "Minimum Time in Stage",
        description: "Candidate must spend minimum 48 hours in stage before advancing",
        rule_type: "requirement",
        conditions: [{ field: "min_time_in_stage", operator: "gte", value: 48 }],
        actions: null,
        allow_override: true,
        override_roles: ["hiring_manager", "hr_admin"],
        priority: 5,
    },
    {
        name: "Auto-Reject Low Scores",
        description: "Automatically reject candidates scoring below 30",
        rule_type: "auto_transition",
        conditions: [{ field: "min_score", operator: "gte", value: 0 }], // always check
        actions: [{ type: "auto_move", params: { targetStage: "Rejected", reason: "Score below threshold" } }],
        allow_override: false,
        override_roles: [],
        priority: 10,
    },
    {
        name: "Notes Required Before Rejection",
        description: "Cannot reject without adding at least 1 note explaining the reason",
        rule_type: "requirement",
        conditions: [{ field: "has_notes", operator: "gte", value: 1 }],
        actions: null,
        allow_override: false,
        override_roles: [],
        priority: 7,
    },
    {
        name: "Rating Required",
        description: "Candidate must be rated (1-5 stars) before advancing",
        rule_type: "requirement",
        conditions: [{ field: "has_rating", operator: "gte", value: 1 }],
        actions: null,
        allow_override: true,
        override_roles: ["hiring_manager", "hr_admin"],
        priority: 6,
    },
    {
        name: "Approval Required for Offer",
        description: "Hiring manager must approve before extending an offer",
        rule_type: "requirement",
        conditions: [{ field: "approval_required", operator: "eq", value: "hiring_manager" }],
        actions: null,
        allow_override: false,
        override_roles: ["hr_admin"],
        priority: 10,
    },
];
