import { mkdir, mkdtemp, readFile, rm, writeFile } from 'node:fs/promises';
import { tmpdir } from 'node:os';
import path from 'node:path';
import { test } from 'node:test';
import assert from 'node:assert/strict';
import {
  ensureDailyWorklogFile,
  isWorklogCreationDue,
  normalizeDailyCreateTime,
  upgradeLegacyWorklogContent,
} from './worklog-automation-utils.js';

test('normalizeDailyCreateTime falls back when value is invalid', () => {
  assert.equal(normalizeDailyCreateTime(undefined), '18:00');
  assert.equal(normalizeDailyCreateTime('bad'), '18:00');
  assert.equal(normalizeDailyCreateTime('09:30'), '09:30');
});

test('isWorklogCreationDue checks KST schedule once per day', () => {
  assert.equal(isWorklogCreationDue(new Date('2026-04-07T08:59:00Z'), '18:00', false), false);
  assert.equal(isWorklogCreationDue(new Date('2026-04-07T09:00:00Z'), '18:00', false), true);
  assert.equal(isWorklogCreationDue(new Date('2026-04-07T09:05:00Z'), '18:00', true), false);
});

test('ensureDailyWorklogFile creates today worklog from template only once', async () => {
  const repoPath = await mkdtemp(path.join(tmpdir(), 'worklog-automation-test-'));
  const templatePath = path.join(repoPath, 'docs', 'templates', 'worklog-template.md');

  try {
    await mkdir(path.dirname(templatePath), { recursive: true });
    await writeFile(templatePath, '# YYYY-MM-DD 작업일지\n\n## 오늘 작업\n\n- \n', 'utf8');

    const worklogPath = await ensureDailyWorklogFile(repoPath, '2026-04-07');
    const firstContent = await readFile(worklogPath, 'utf8');
    assert.equal(firstContent.includes('# 2026-04-07 작업일지'), true);

    await writeFile(worklogPath, '# keep\n', 'utf8');
    await ensureDailyWorklogFile(repoPath, '2026-04-07');
    const secondContent = await readFile(worklogPath, 'utf8');
    assert.equal(secondContent, '# keep\n');
  } finally {
    await rm(repoPath, { recursive: true, force: true });
  }
});

test('upgradeLegacyWorklogContent replaces legacy source placeholder with file scoped format', () => {
  const legacyContent = `# 2026-04-07 작업일지

## 상세 작업 내역

- 

## 소스

- 요약 설명
- \`path/to/file.tsx\`: 변경 또는 신규 추가 목적과 핵심 내용을 한 줄로 정리

\`\`\`diff
# 핵심 diff를 1~3개 블록으로 기록
- before
+ after
\`\`\`
`;

  const upgraded = upgradeLegacyWorklogContent(legacyContent);
  assert.equal(upgraded.includes('### 파일 1: `path/to/file.tsx`'), true);
  assert.equal(upgraded.includes('# 이 파일의 raw diff'), true);
  assert.equal(upgraded.includes('`상세 작업 내역`에는 파일 목록이나 raw diff를 다시 쓰지 않음'), true);
  assert.equal(upgraded.includes('`전체소스 / raw diff`'), true);
});

test('upgradeLegacyWorklogContent upgrades screenshot guidance to require full screenshot', () => {
  const legacyContent = `# 2026-04-07 작업일지

## 스크린샷

- 저장소 기준 연결된 스크린샷 없음
`;

  const upgraded = upgradeLegacyWorklogContent(legacyContent);
  assert.equal(upgraded.includes('- 전체 화면 스크린샷 1장은 필수'), true);
  assert.equal(upgraded.includes('- 위젯/컴포넌트 단위 부분 스크린샷은 필요한 만큼 추가'), true);
});

test('upgradeLegacyWorklogContent removes obsolete auto-generated summary sections', () => {
  const legacyContent = `# 2026-04-07 작업일지

## 오늘 작업

- 작업 정리

## 커밋 목록 (2026-04-07, KST 기준)

- \`abc1234\` example

## 변경 요약

- 자동 수집 요약

## 변경 통계 (파일별, KST 기준)

- src/example.ts (+1/-1)

## 라인 통계 (KST 기준)

- 추가: 1줄

## 변경/신규 파일

- M src/example.ts
`;

  const upgraded = upgradeLegacyWorklogContent(legacyContent);
  assert.equal(upgraded.includes('## 커밋 목록'), false);
  assert.equal(upgraded.includes('## 변경 요약'), false);
  assert.equal(upgraded.includes('## 변경 통계'), false);
  assert.equal(upgraded.includes('## 라인 통계'), false);
  assert.equal(upgraded.includes('## 변경/신규 파일'), true);
});
