import { getSession } from "../lib/neo4j.js";
// Cross-process agreement: these values must match neo4j-store.ts
const INJECTION_THRESHOLD = 0.4;
const MAX_SUMMARY_PREFERENCES = 30;
export async function profileRead(params) {
    const { accountId, userId, detail } = params;
    const session = getSession();
    try {
        const result = await session.run(`
      OPTIONAL MATCH (up:UserProfile {accountId: $accountId, userId: $userId})
      OPTIONAL MATCH (up)-[:HAS_PREFERENCE]->(pref:Preference)
      WHERE pref.confidence >= $threshold
      WITH up, pref
      ORDER BY pref.confidence DESC
      WITH up, collect(pref) AS allPrefs
      WITH up, allPrefs[0..$limit] AS prefs
      RETURN up, prefs
      `, {
            accountId,
            userId,
            threshold: INJECTION_THRESHOLD,
            limit: MAX_SUMMARY_PREFERENCES,
        });
        if (result.records.length === 0 || !result.records[0].get("up")) {
            if (detail) {
                return {
                    profile: null,
                    preferences: [],
                    summary: "No profile found.",
                    stats: { totalPreferences: 0, explicitCount: 0, behaviouralCount: 0, highConfidence: 0, lowConfidence: 0 },
                };
            }
            return { profile: null, preferences: [], summary: "No profile found." };
        }
        const record = result.records[0];
        const upNode = record.get("up");
        const profileProps = { ...upNode.properties };
        delete profileProps.embedding;
        const prefNodes = record.get("prefs");
        const preferences = prefNodes.map((p) => ({
            preferenceId: p.properties.preferenceId,
            category: p.properties.category,
            key: p.properties.key,
            value: p.properties.value,
            confidence: p.properties.confidence,
            source: p.properties.source,
            observedAt: p.properties.observedAt,
        }));
        if (!detail) {
            const summary = formatProfileSummary(profileProps, preferences);
            return { profile: profileProps, preferences, summary };
        }
        // Detail mode: fetch evidence trail for each preference
        const prefIds = preferences.map((p) => p.preferenceId);
        const evidenceMap = new Map();
        if (prefIds.length > 0) {
            const evidenceResult = await session.run(`
        UNWIND $prefIds AS pid
        MATCH (pref:Preference {preferenceId: pid})-[:OBSERVED_IN]->(conv:Conversation)
        RETURN pref.preferenceId AS preferenceId,
               collect({name: conv.name, date: conv.createdAt}) AS evidence
        `, { prefIds });
            for (const r of evidenceResult.records) {
                const pid = r.get("preferenceId");
                const rawEvidence = r.get("evidence");
                evidenceMap.set(pid, rawEvidence.map((e) => ({ conversationName: e.name, date: e.date })));
            }
        }
        const detailedPreferences = preferences.map((p) => ({
            ...p,
            evidence: evidenceMap.get(p.preferenceId) ?? [],
        }));
        const stats = {
            totalPreferences: preferences.length,
            explicitCount: preferences.filter((p) => p.source === "explicit").length,
            behaviouralCount: preferences.filter((p) => p.source === "behavioural").length,
            highConfidence: preferences.filter((p) => p.confidence >= 0.7).length,
            lowConfidence: preferences.filter((p) => p.confidence < 0.5).length,
        };
        const summary = formatDetailedSummary(profileProps, detailedPreferences, stats);
        return { profile: profileProps, preferences: detailedPreferences, summary, stats };
    }
    finally {
        await session.close();
    }
}
const CATEGORY_LABELS = {
    communication: "Communication",
    scheduling: "Scheduling",
    decision: "Decisions",
    workflow: "Workflow",
    content: "Content",
    interaction: "Interaction patterns",
};
// Profile summary format — also implemented in neo4j-store.ts (loadUserProfile).
// Changes here must be reflected there and vice versa.
export function formatProfileSummary(profile, preferences) {
    const name = profile.givenName || "Owner";
    const role = profile.role ? ` (${profile.role})` : "";
    const tz = profile.timezone ? ` — ${profile.timezone}` : "";
    const locale = profile.locale ? `, ${profile.locale}` : "";
    const expertise = profile.expertise
        ? `\nExpertise: ${typeof profile.expertise === "string"
            ? profile.expertise
            : JSON.stringify(profile.expertise)}`
        : "";
    const lines = [`## About the Owner\n`];
    lines.push(`${name}${role}${tz}${locale}${expertise}\n`);
    // Group by category
    const categories = {};
    for (const pref of preferences) {
        if (!categories[pref.category])
            categories[pref.category] = [];
        categories[pref.category].push(pref);
    }
    // How they work section
    const workCategories = ["communication", "scheduling", "decision", "workflow", "content"];
    const workPrefs = workCategories.filter((c) => categories[c]);
    if (workPrefs.length > 0) {
        lines.push(`### How they work`);
        for (const cat of workPrefs) {
            const label = CATEGORY_LABELS[cat] || cat;
            const items = categories[cat].map((p) => p.value).join("; ");
            lines.push(`- ${label}: ${items}`);
        }
        lines.push("");
    }
    // Interaction section
    if (categories.interaction) {
        lines.push(`### Interaction patterns`);
        for (const pref of categories.interaction) {
            lines.push(`- ${pref.value}`);
        }
        lines.push("");
    }
    return lines.join("\n");
}
// Detailed summary for "what do you know about me?" — includes confidence,
// source, and evidence trail per preference.
function formatDetailedSummary(profile, preferences, stats) {
    const name = profile.givenName || "Owner";
    const role = profile.role ? ` (${profile.role})` : "";
    const tz = profile.timezone ? ` — ${profile.timezone}` : "";
    const locale = profile.locale ? `, ${profile.locale}` : "";
    const expertise = profile.expertise
        ? `\nExpertise: ${typeof profile.expertise === "string"
            ? profile.expertise
            : JSON.stringify(profile.expertise)}`
        : "";
    const lines = [`## What I Know About You\n`];
    lines.push(`${name}${role}${tz}${locale}${expertise}\n`);
    lines.push(`Memory: ${stats.totalPreferences} preferences ` +
        `(${stats.explicitCount} you told me, ${stats.behaviouralCount} I observed). ` +
        `${stats.highConfidence} high-confidence, ${stats.lowConfidence} fading.\n`);
    // Group by category
    const categories = {};
    for (const pref of preferences) {
        if (!categories[pref.category])
            categories[pref.category] = [];
        categories[pref.category].push(pref);
    }
    const allCategories = ["communication", "scheduling", "decision", "workflow", "content", "interaction"];
    for (const cat of allCategories) {
        if (!categories[cat])
            continue;
        const label = CATEGORY_LABELS[cat] || cat;
        lines.push(`### ${label}`);
        for (const pref of categories[cat]) {
            const conf = confidenceLabel(pref.confidence);
            const src = pref.source === "explicit" ? "you said" : "observed";
            const date = pref.observedAt ? ` (${pref.observedAt.slice(0, 10)})` : "";
            lines.push(`- **${pref.key}**: ${pref.value} — ${conf}, ${src}${date}`);
            if (pref.evidence.length > 0) {
                const evidenceStrs = pref.evidence
                    .map((e) => e.conversationName || e.date?.slice(0, 10) || "unknown")
                    .slice(0, 3);
                lines.push(`  Evidence: ${evidenceStrs.join(", ")}`);
            }
        }
        lines.push("");
    }
    return lines.join("\n");
}
function confidenceLabel(confidence) {
    if (confidence >= 0.8)
        return "strong";
    if (confidence >= 0.6)
        return "moderate";
    if (confidence >= 0.4)
        return "fading";
    return "weak";
}
//# sourceMappingURL=profile-read.js.map