import { isThinkingPartnerRequest } from './promptDetection';
import { extractEvidenceFilesFromProjectKnowledge, extractPriorityPreviewFiles } from './projectEvidence';
import { buildThinkingPartnerResponseContract } from './thinkingPartnerContract';

/**
 * "자비스 프로젝트 브리프" — 사용자가 thinking-partner 톤의 메타 질문을 던지면
 * 모델에게 *어떤 프로젝트* 의 *어떤 증거 파일* 을 보고 답해야 하는지 알려주는
 * 시스템 prompt prepend 블록.
 *
 * 우선순위: 직전 localPathContext (실제 path access 성공) > project knowledge
 * record. 둘 다 없으면 "성급한 단정 금지" 안내 + thinking-partner contract 만
 * 붙여 반환.
 *
 * Stateless — agent.ts 의 private 메서드를 그대로 추출. 의존: thinking-partner
 * detection + evidence file 추출 두 헬퍼 (역시 이미 추출됨) + response contract.
 */
export function buildJarvisProjectBriefContext(
    prompt: string,
    localPathContext: string,
    recentProjectKnowledgeContext: string,
): string {
    if (!isThinkingPartnerRequest(prompt)) {
        return '';
    }

    const sourceContext = localPathContext && localPathContext.includes('Access: succeeded')
        ? localPathContext
        : recentProjectKnowledgeContext;
    if (!sourceContext) {
        return [
            '[JARVIS PROJECT BRIEF]',
            'No concrete local project brief is available yet.',
            'Use the conversation and Second Brain cautiously. If the user asks about a project architecture, ask for or inspect the project path before making strong claims.',
            '',
            buildThinkingPartnerResponseContract(),
        ].join('\n');
    }

    const projectPath = sourceContext.match(/Path:\s*(.+)/)?.[1]?.trim()
        || sourceContext.match(/Repository:\s*`([^`]+)`/)?.[1]?.trim()
        || sourceContext.match(/project evidence:\s*([^\s]+)/i)?.[1]?.trim()
        || 'current project';
    const evidenceFiles = sourceContext.includes('Priority file previews:')
        ? extractPriorityPreviewFiles(sourceContext).slice(0, 10)
        : extractEvidenceFilesFromProjectKnowledge(sourceContext).slice(0, 10);
    const treeMatch = sourceContext.match(/Scanned tree:\n([\s\S]*?)(?:\nPriority file previews:|$)/);
    const treePreview = treeMatch?.[1]?.trim().split('\n').slice(0, 30).join('\n') || '';

    return [
        '[JARVIS PROJECT BRIEF]',
        `Project evidence target: ${projectPath}`,
        evidenceFiles.length
            ? `Evidence files available:\n${evidenceFiles.map((file) => `- ${file}`).join('\n')}`
            : 'Evidence files available: not enough concrete file markers were found.',
        treePreview ? `Visible structure preview:\n${treePreview}` : '',
        '',
        buildThinkingPartnerResponseContract(),
    ].filter(Boolean).join('\n');
}
