#!/usr/bin/env bash
# 3계층 런타임 검증 스크립트
# Level 1: 프로세스 상태
# Level 2: API 응답
# Level 3: 데이터 정합성

set -euo pipefail

PIPELINE_STATUS_FILE="/home/jay/workspace/memory/pipeline-status.json"
TASK_TIMERS_FILE="/home/jay/workspace/memory/task-timers.json"
TIMESTAMP=$(date -u +"%Y-%m-%dT%H:%M:%S")

# 각 체크 결과를 저장할 배열
declare -A CHECK_STATUS
declare -A CHECK_DETAIL

# ─────────────────────────────────────────────
# Level 1 — 프로세스 상태
# ─────────────────────────────────────────────

# Check 1: cokacdir 프로세스 확인
if pgrep -f cokacdir > /dev/null 2>&1; then
    PIDS=$(pgrep -f cokacdir | tr '\n' ',' | sed 's/,$//')
    CHECK_STATUS["cokacdir_process"]="ok"
    CHECK_DETAIL["cokacdir_process"]="프로세스 실행 중 (PID: ${PIDS})"
else
    CHECK_STATUS["cokacdir_process"]="fail"
    CHECK_DETAIL["cokacdir_process"]="cokacdir 프로세스를 찾을 수 없음"
fi

# Check 2: 포트 8000 확인
if ss -tlnp 2>/dev/null | grep -q ':8000'; then
    PORT_DETAIL=$(ss -tlnp 2>/dev/null | grep ':8000' | head -1 | awk '{print $1, $4}')
    CHECK_STATUS["port_8000"]="ok"
    CHECK_DETAIL["port_8000"]="포트 8000 리스닝 중 (${PORT_DETAIL})"
else
    CHECK_STATUS["port_8000"]="fail"
    CHECK_DETAIL["port_8000"]="포트 8000에서 리스닝하는 서비스 없음"
fi

# ─────────────────────────────────────────────
# Level 2 — API 응답
# ─────────────────────────────────────────────

# Check 3: /api/status 엔드포인트 확인
API_RESPONSE=$(curl -s --max-time 5 http://localhost:8000/api/status 2>/dev/null || true)
if echo "${API_RESPONSE}" | python3 -c "import sys, json; d=json.load(sys.stdin); sys.exit(0 if 'status' in d else 1)" 2>/dev/null; then
    STATUS_VAL=$(echo "${API_RESPONSE}" | python3 -c "import sys, json; d=json.load(sys.stdin); print(d.get('status',''))" 2>/dev/null || echo "unknown")
    CHECK_STATUS["api_status_endpoint"]="ok"
    CHECK_DETAIL["api_status_endpoint"]="JSON 응답 정상, status=${STATUS_VAL}"
else
    CHECK_STATUS["api_status_endpoint"]="fail"
    if [ -z "${API_RESPONSE}" ]; then
        CHECK_DETAIL["api_status_endpoint"]="응답 없음 또는 타임아웃"
    else
        CHECK_DETAIL["api_status_endpoint"]="JSON 파싱 실패 또는 'status' 키 없음 (응답: ${API_RESPONSE:0:100})"
    fi
fi

# Check 4: /dashboard/ 엔드포인트 확인
DASHBOARD_HTTP_CODE=$(curl -s -o /tmp/health_dashboard_body.tmp -w "%{http_code}" --max-time 5 http://localhost:8000/dashboard/ 2>/dev/null || echo "000")
DASHBOARD_BODY=$(cat /tmp/health_dashboard_body.tmp 2>/dev/null || echo "")
rm -f /tmp/health_dashboard_body.tmp

if [ "${DASHBOARD_HTTP_CODE}" = "200" ] && echo "${DASHBOARD_BODY}" | grep -qi '<html'; then
    CHECK_STATUS["dashboard_endpoint"]="ok"
    CHECK_DETAIL["dashboard_endpoint"]="HTTP 200 및 HTML 응답 확인됨"
else
    CHECK_STATUS["dashboard_endpoint"]="fail"
    if [ "${DASHBOARD_HTTP_CODE}" = "000" ]; then
        CHECK_DETAIL["dashboard_endpoint"]="연결 실패 또는 타임아웃"
    elif [ "${DASHBOARD_HTTP_CODE}" != "200" ]; then
        CHECK_DETAIL["dashboard_endpoint"]="HTTP ${DASHBOARD_HTTP_CODE} 응답 (200 아님)"
    else
        CHECK_DETAIL["dashboard_endpoint"]="HTTP 200이나 HTML 태그 없음"
    fi
fi

# ─────────────────────────────────────────────
# Level 3 — 데이터 정합성
# ─────────────────────────────────────────────

# Check 5: task-timers.json running 상태 작업 수 카운트
if [ -f "${TASK_TIMERS_FILE}" ]; then
    RUNNING_COUNT=$(python3 -c "
import json, sys
try:
    with open('${TASK_TIMERS_FILE}', 'r', encoding='utf-8') as f:
        data = json.load(f)
    tasks = data.get('tasks', {})
    running = sum(1 for t in tasks.values() if t.get('status') == 'running')
    print(running)
except Exception as e:
    print('ERROR:' + str(e))
" 2>/dev/null || echo "ERROR:python3 실행 실패")

    if echo "${RUNNING_COUNT}" | grep -q '^ERROR:'; then
        CHECK_STATUS["task_timers_consistency"]="fail"
        CHECK_DETAIL["task_timers_consistency"]="파일 파싱 오류: ${RUNNING_COUNT#ERROR:}"
    else
        CHECK_STATUS["task_timers_consistency"]="ok"
        CHECK_DETAIL["task_timers_consistency"]="running 상태 작업 수: ${RUNNING_COUNT}개"
    fi
else
    CHECK_STATUS["task_timers_consistency"]="fail"
    CHECK_DETAIL["task_timers_consistency"]="${TASK_TIMERS_FILE} 파일 없음"
fi

# Check 6: sync-check.py 실행 결과 확인
if python3 /home/jay/workspace/sync-check.py > /tmp/health_sync_check.tmp 2>&1; then
    CHECK_STATUS["org_sync_check"]="ok"
    CHECK_DETAIL["org_sync_check"]="sync-check.py 종료코드 0 (정상)"
else
    SYNC_EXIT_CODE=$?
    SYNC_OUTPUT=$(cat /tmp/health_sync_check.tmp 2>/dev/null | head -3 | tr '\n' ' ')
    CHECK_STATUS["org_sync_check"]="fail"
    CHECK_DETAIL["org_sync_check"]="sync-check.py 종료코드 ${SYNC_EXIT_CODE}: ${SYNC_OUTPUT}"
fi
rm -f /tmp/health_sync_check.tmp

# ─────────────────────────────────────────────
# JSON 출력 생성 및 summary 계산
# ─────────────────────────────────────────────

PASS_COUNT=0
FAIL_COUNT=0

for key in cokacdir_process port_8000 api_status_endpoint dashboard_endpoint task_timers_consistency org_sync_check; do
    if [ "${CHECK_STATUS[$key]}" = "ok" ]; then
        PASS_COUNT=$((PASS_COUNT + 1))
    else
        FAIL_COUNT=$((FAIL_COUNT + 1))
    fi
done

TOTAL_COUNT=6

# Python3로 JSON 직렬화 (특수문자 이스케이프 처리)
HEALTH_JSON=$(python3 -c "
import json
from datetime import datetime

checks = [
    {
        'name': 'cokacdir_process',
        'status': '${CHECK_STATUS[cokacdir_process]}',
        'detail': '''${CHECK_DETAIL[cokacdir_process]}'''
    },
    {
        'name': 'port_8000',
        'status': '${CHECK_STATUS[port_8000]}',
        'detail': '''${CHECK_DETAIL[port_8000]}'''
    },
    {
        'name': 'api_status_endpoint',
        'status': '${CHECK_STATUS[api_status_endpoint]}',
        'detail': '''${CHECK_DETAIL[api_status_endpoint]}'''
    },
    {
        'name': 'dashboard_endpoint',
        'status': '${CHECK_STATUS[dashboard_endpoint]}',
        'detail': '''${CHECK_DETAIL[dashboard_endpoint]}'''
    },
    {
        'name': 'task_timers_consistency',
        'status': '${CHECK_STATUS[task_timers_consistency]}',
        'detail': '''${CHECK_DETAIL[task_timers_consistency]}'''
    },
    {
        'name': 'org_sync_check',
        'status': '${CHECK_STATUS[org_sync_check]}',
        'detail': '''${CHECK_DETAIL[org_sync_check]}'''
    },
]

result = {
    'timestamp': '${TIMESTAMP}',
    'checks': checks,
    'summary': {
        'total': ${TOTAL_COUNT},
        'pass': ${PASS_COUNT},
        'fail': ${FAIL_COUNT}
    }
}

print(json.dumps(result, ensure_ascii=False, indent=2))
")

# stdout에 JSON 출력
echo "${HEALTH_JSON}"

# ─────────────────────────────────────────────
# pipeline-status.json 업데이트
# ─────────────────────────────────────────────

python3 -c "
import json
import fcntl
from pathlib import Path

pipeline_file = Path('${PIPELINE_STATUS_FILE}')
pipeline_file.parent.mkdir(parents=True, exist_ok=True)

# 기존 파일 읽기 또는 새로 생성
if pipeline_file.exists():
    with open(pipeline_file, 'r', encoding='utf-8') as f:
        fcntl.flock(f, fcntl.LOCK_SH)
        try:
            pipeline_data = json.load(f)
        except json.JSONDecodeError:
            pipeline_data = {}
        finally:
            fcntl.flock(f, fcntl.LOCK_UN)
else:
    pipeline_data = {}

# 기본 구조 보장
if 'active_tasks' not in pipeline_data:
    pipeline_data['active_tasks'] = []
if 'last_health_check' not in pipeline_data:
    pipeline_data['last_health_check'] = None

health_result = ${HEALTH_JSON}

pipeline_data['last_updated'] = '${TIMESTAMP}'
pipeline_data['last_health_check'] = health_result

with open(pipeline_file, 'w', encoding='utf-8') as f:
    fcntl.flock(f, fcntl.LOCK_EX)
    try:
        json.dump(pipeline_data, f, ensure_ascii=False, indent=2)
    finally:
        fcntl.flock(f, fcntl.LOCK_UN)
" 2>/dev/null || true

# ─────────────────────────────────────────────
# 종료 코드 결정
# ─────────────────────────────────────────────

if [ "${FAIL_COUNT}" -gt 0 ]; then
    exit 1
else
    exit 0
fi
