import type {
    BugRecord,
    DecisionRecord,
    DevelopmentLog,
    DiscussionRecord,
    PlanningDocument,
} from '../../features/projectChronicle';
import { summarizeTextForWiki } from './textHelpers';
import { extractChangedFilesFromText } from './autoChronicleClassifier';

/**
 * 자동 chronicle 기록 5가지 record type 의 *payload* 빌더. 모두 pure — 사용자
 * 메시지/응답/title/createdAt 만 받으면 ProjectChronicleManager.writeXxx() 에 그대로
 * 넘길 수 있는 record body 객체를 반환.
 *
 * 옛 코드: sidebarProvider 의 `_autoWriteChronicleAfterPrompt` 안 5분기 if/else 가
 * inline 으로 payload 를 만들고 있었음 (~70줄). 분류기는 이미 `autoChronicleClassifier`
 * 로 분리됐고, 이 모듈은 *그 결정 이후의 payload 조립* 만 책임.
 *
 * Provider 는 분류 → 이 모듈로 payload 받음 → `this._chronicle.writeXxx(profile, payload, [number])`
 * 흐름. 빌더는 instance state 없고 `summarizeTextForWiki` / `extractChangedFilesFromText`
 * 등 기존 builder 만 사용.
 */

export function buildAutoBugRecord(
    title: string,
    summary: string,
    latestUser: string,
    createdAt: string,
): BugRecord {
    return {
        title,
        symptom: summarizeTextForWiki(latestUser || 'Issue was detected during the conversation.'),
        cause: 'Captured automatically from the current conversation. Confirm root cause during follow-up review if needed.',
        fix: summary,
        prevention: 'Keep automatic records tied to the active project and verify the relevant test or reproduction path.',
        createdAt,
    };
}

export function buildAutoPlanningRecord(
    title: string,
    summary: string,
    latestUser: string,
    createdAt: string,
): PlanningDocument {
    return {
        featureName: title,
        purpose: 'Capture the current planning or architecture direction before implementation continues.',
        background: summary,
        userIntent: summarizeTextForWiki(latestUser),
        sourceRequest: latestUser || 'No user request captured in the current chat.',
        scope: ['Continue from the active project conversation.', 'Use the selected project record folder automatically.'],
        outOfScope: ['Manual record type selection.', 'Blocking the user with record-writing prompts.'],
        developmentDirection: summary,
        dependencyStrategy: 'Prefer existing project modules and local Markdown records.',
        expectedValue: 'Future work can resume with the latest project intent and reasoning preserved.',
        successCriteria: ['The record is saved automatically after a meaningful project turn.', 'The record stays under the active project.'],
        developerInstruction: 'Use this record as lightweight context for the next development or review pass.',
        createdAt,
    };
}

export function buildAutoDecisionRecord(
    title: string,
    summary: string,
    latestUser: string,
    createdAt: string,
): DecisionRecord {
    return {
        title,
        status: 'accepted',
        context: summarizeTextForWiki(latestUser),
        decision: summary,
        reason: 'Captured automatically because the conversation contained decision-oriented language.',
        alternatives: [],
        consequences: ['Future prompts should treat this as project context unless the user changes direction.'],
        createdAt,
    };
}

export function buildAutoDevelopmentRecord(
    title: string,
    summary: string,
    latestAssistant: string,
    createdAt: string,
): DevelopmentLog {
    return {
        featureName: title,
        purpose: 'Record the implementation or verification outcome from the current conversation.',
        implementationSummary: summary,
        architecture: 'Captured automatically from the assistant response and active project context.',
        changedFiles: extractChangedFilesFromText(latestAssistant),
        dependencyNotes: 'No new dependency note was captured automatically.',
        bugs: [],
        lessons: ['Automatic project records should be generated in the background when the turn contains durable project knowledge.'],
        createdAt,
    };
}

export function buildAutoDiscussionRecord(
    title: string,
    summary: string,
    latestUser: string,
    createdAt: string,
): DiscussionRecord {
    return {
        title,
        userRequest: summarizeTextForWiki(latestUser || 'No user request captured in the current chat.'),
        interpretedIntent: 'Capture a meaningful project discussion automatically instead of requiring manual record selection.',
        questions: [],
        discussions: [summary],
        decisions: [],
        createdAt,
    };
}
