> ## Documentation Index
> Fetch the complete documentation index at: https://docs.sajuapi.dev/llms.txt
> Use this file to discover all available pages before exploring further.

# 일일 운세 생성

사주 데이터를 기반으로 AI가 일일 투자 운세를 생성합니다.

<Note>
  사주 데이터는 클라이언트에서 SajuCalculator.js를 사용하여 미리 계산해야 합니다.
</Note>

***

## Request Body

<ParamField body="saju" type="SajuResult" required>
  클라이언트에서 계산한 사주 데이터 객체입니다. SajuCalculator.js의 반환값을 그대로 사용합니다.
</ParamField>

<ParamField body="userName" type="string" required>
  사용자 이름입니다. 운세 메시지에 포함됩니다.
</ParamField>

<ParamField body="date" type="string" required>
  운세를 볼 날짜입니다. YYYY-MM-DD 형식입니다.
</ParamField>

<ParamField body="model" type="string" default="haiku">
  사용할 AI 모델입니다. `haiku`, `sonnet`, `gpt4o`, `gemini` 중 하나입니다.
</ParamField>

<ParamField body="type" type="string">
  요청할 데이터 유형입니다. 생략하면 모든 데이터를 반환합니다.

  * `character`: 투자 성격 분석
  * `tendency`: 투자 성향 분석
  * `fortune`: 오늘의 운세
  * `radar`: 레이더 차트 데이터
  * `compare`: 모든 모델 비교 (4개 모델 동시 호출)
</ParamField>

***

## Response

### 성공

운세 생성에 성공하면 FortuneResponse 객체가 반환됩니다.

### 실패

| 상태 코드 | 설명          |
| ----- | ----------- |
| 400   | 필수 파라미터 누락  |
| 500   | AI 모델 호출 실패 |

***

## 요청 예시

<CodeGroup>
  ```javascript JavaScript theme={null}
  // SajuCalculator로 사주 계산
  const saju = SajuCalculator.calculate({
    year: 1990,
    month: 3,
    day: 15,
    hour: 14,
    gender: 'male'
  });

  // 운세 요청
  const response = await fetch('/api/daily-fortune', {
    method: 'POST',
    headers: { 'Content-Type': 'application/json' },
    body: JSON.stringify({
      saju,
      userName: '김철수',
      date: '2025-01-16',
      model: 'haiku',
      type: 'fortune'
    })
  });

  const { success, data, meta } = await response.json();
  ```

  ```python Python theme={null}
  import requests

  # 사주 데이터 (클라이언트에서 계산된 값)
  saju = {
      "pillars": {
          "year": {"stem": {"hangul": "경"}, "branch": {"hangul": "오"}},
          "month": {"stem": {"hangul": "기"}, "branch": {"hangul": "묘"}},
          "day": {"stem": {"hangul": "병"}, "branch": {"hangul": "인"}},
          "hour": None
      },
      "dayMaster": {"name": "병화", "element": "fire"},
      "elements": {"wood": 2, "fire": 3, "earth": 1, "metal": 1, "water": 1},
      "dominantElement": "fire",
      "weakestElement": "water",
      "zodiac": "말"
  }

  response = requests.post(
      'https://sajuapi.dev/api/daily-fortune',
      json={
          'saju': saju,
          'userName': '김철수',
          'date': '2025-01-16',
          'model': 'haiku',
          'type': 'fortune'
      }
  )

  result = response.json()
  ```

  ```bash cURL theme={null}
  curl -X POST https://sajuapi.dev/api/daily-fortune \
    -H "Content-Type: application/json" \
    -d '{
      "saju": {
        "pillars": {
          "day": {"stem": {"hangul": "병"}}
        },
        "dayMaster": {"name": "병화", "element": "fire"},
        "elements": {"wood": 2, "fire": 3, "earth": 1, "metal": 1, "water": 1},
        "weakestElement": "water"
      },
      "userName": "김철수",
      "date": "2025-01-16",
      "model": "haiku",
      "type": "fortune"
    }'
  ```
</CodeGroup>

***

## 응답 예시

```json theme={null}
{
  "success": true,
  "data": {
    "character": {
      "title": "태양의 기운",
      "dayMaster": "병화",
      "dayMasterHanja": "丙",
      "elementName": "태양",
      "emoji": "☀️",
      "identity": "밝고 따뜻한 성격으로 주변을 환하게 밝히는 리더십을 가지고 있습니다.",
      "investmentIdentity": "적극적이고 과감한 투자 성향으로, 트렌드를 빠르게 파악합니다."
    },
    "investmentTendency": {
      "scores": {
        "riskTolerance": 75,
        "longTermAptitude": 60,
        "trendSensitivity": 85
      },
      "summary": "화(火)의 기운이 강해 빠른 판단과 실행력이 뛰어납니다.",
      "warning": "충동적인 결정을 피하고 냉정함을 유지하세요."
    },
    "todayFortune": {
      "date": "2025-01-16",
      "formattedDate": "2025년 1월 16일 (목)",
      "dayElement": "earth",
      "score": 78,
      "overallAnalysis": "오늘은 안정적인 투자가 유리한 날입니다. 토(土)의 기운이 화(火)를 받쳐주어 균형 잡힌 판단이 가능합니다.",
      "actionItems": [
        { "type": "do", "text": "분산 투자 전략 고려" },
        { "type": "do", "text": "장기 보유 종목 점검" },
        { "type": "avoid", "text": "고위험 레버리지 상품" },
        { "type": "avoid", "text": "충동적인 단타 매매" }
      ],
      "timing": {
        "best": "14:00-16:00",
        "avoid": "09:00-11:00",
        "reason": "오후에 화(火)의 기운이 안정되어 냉정한 판단이 가능합니다."
      }
    },
    "investmentFortune": {
      "shortTerm": {
        "message": "단기적으로는 소액 분산 투자가 유리합니다.",
        "warning": "급등주 추격 매수는 자제하세요."
      },
      "longTerm": {
        "message": "장기적으로 안정적인 대형주 중심의 포트폴리오가 좋습니다.",
        "advice": "월 적립식 투자를 고려해보세요."
      },
      "example": "삼성전자, SK하이닉스 등 대형 우량주"
    },
    "whyExplanation": "오늘의 천간이 토(土)로, 당신의 일주인 병화(丙火)와 상생 관계입니다."
  },
  "generatedAt": "2025-01-16T09:00:00Z",
  "meta": {
    "model": "haiku",
    "requestId": "req_abc123def456",
    "costPerCall": 0.013,
    "durationMs": 1250,
    "cache": {
      "hits": ["character", "tendency"],
      "misses": ["fortune"]
    }
  }
}
```

***

## FortuneData 객체

| 필드                   | 타입     | 설명              |
| -------------------- | ------ | --------------- |
| `character`          | object | 투자 성격 분석 결과입니다. |
| `investmentTendency` | object | 투자 성향 분석 결과입니다. |
| `todayFortune`       | object | 오늘의 운세입니다.      |
| `investmentFortune`  | object | 투자 관련 조언입니다.    |
| `whyExplanation`     | string | 운세 해설입니다.       |

***

## 모델 비교 (type: compare)

`type: 'compare'`를 사용하면 4개 모델의 결과를 동시에 받을 수 있습니다.

```javascript theme={null}
const response = await fetch('/api/daily-fortune', {
  method: 'POST',
  headers: { 'Content-Type': 'application/json' },
  body: JSON.stringify({
    saju,
    userName: '김철수',
    date: '2025-01-16',
    type: 'compare'  // 4개 모델 동시 호출
  })
});

// 응답에 각 모델별 결과가 포함됨
const { data } = await response.json();
// data.haiku, data.sonnet, data.gpt4o, data.gemini
```

<Warning>
  `compare` 타입은 4개 모델을 동시에 호출하므로 비용이 4배입니다.
  총 비용: $0.013 + $0.066 + $0.050 + $0.010 = \$0.139
</Warning>
