<script setup lang="ts">
import { computed, ref } from 'vue'
import PageLayout from '../../../shared/ui/layouts/PageLayout.vue'
import QueryStateBoundary from '../../../shared/ui/QueryStateBoundary.vue'
import { KsButton, KsCheckbox, KsFormGrid, KsFormSection, KsNumberField } from '../../../shared/ui/components'
import PolicyTracePanel from '../components/PolicyTracePanel.vue'
import { useEvaluateResearchSellPolicy } from '../queries'
import type { ResearchSellPolicyCommand } from '../api'

const mutation = useEvaluateResearchSellPolicy()
const hardImpairmentApproved = ref(false)
const capitalFloorBreached = ref(false)
const gapBelowFloorAtr = ref(1.6)
const consecutiveCloseBreaches = ref(0)
const lastCommand = ref<ResearchSellPolicyCommand | null>(null)

const isBusy = computed(() => mutation.isPending.value)

function createCommand(): ResearchSellPolicyCommand {
  const asOf = new Date().toISOString()
  return {
    idempotencyKey: crypto.randomUUID(),
    request: {
      positionLotId: '00000000-0000-0000-0000-000000000001',
      cycleId: '00000000-0000-0000-0000-000000000002',
      evidenceId: 'sample-evidence',
      datasetId: 'sample-dataset',
      modelVersion: 'research-v12.2',
      configVersion: 'proposal-v12.2',
      codeSha: 'sample-code-sha',
      asOf,
      publishedAtCutoff: asOf,
      currentSecurityPortfolioWeight: 0.6,
      currentLotPortfolioWeight: 0.2,
      strategicCoreFloorWeight: 0.3,
      hardImpairmentApproved: hardImpairmentApproved.value,
      capitalFloorBreached: capitalFloorBreached.value,
      survivalSellRatioOfLot: 0.5,
      gapBelowFloorAtr: gapBelowFloorAtr.value,
      consecutiveCloseBreaches: consecutiveCloseBreaches.value,
      cooldownSatisfied: true,
      concentrationSellRatioOfLot: 0,
      opportunityEdgeLowerBound: 0,
      opportunitySellRatioOfLot: 0
    }
  }
}

function run() {
  const command = createCommand()
  lastCommand.value = command
  mutation.mutate(command)
}

function retry() {
  if (lastCommand.value) mutation.mutate(lastCommand.value)
}
</script>

<template>
  <PageLayout title="매도 정책 연구 콘솔" subtitle="순수 정책 계약과 우선순위를 확인하는 연구 전용 화면입니다. 고객 제안·공개·주문 기능과 연결되지 않습니다." status="RESEARCH_CANDIDATE_NOT_PRODUCTION · 자동주문 OFF">
    <form @submit.prevent="run">
      <KsFormSection title="연구 입력 벡터">
        <KsFormGrid :columns="2" aria-label="연구 입력 벡터">
          <KsCheckbox v-model="hardImpairmentApproved" label="Hard impairment 승인" :disabled="isBusy" />
          <KsCheckbox v-model="capitalFloorBreached" label="자본바닥 위반" :disabled="isBusy" />
          <KsNumberField v-model="gapBelowFloorAtr" label="보호선 이탈 ATR" :min="0" :max-fraction-digits="2" :disabled="isBusy" />
          <KsNumberField v-model="consecutiveCloseBreaches" label="연속 종가 이탈" :min="0" :max-fraction-digits="0" :disabled="isBusy" />
        </KsFormGrid>
        <template #actions>
          <KsButton type="submit" label="정책 평가" :loading="isBusy" />
        </template>
      </KsFormSection>
    </form>

    <QueryStateBoundary
      :loading="isBusy"
      :error="mutation.error.value as Error | null"
      :empty="!mutation.data.value"
      @retry="retry"
    >
      <dl v-if="mutation.data.value" class="ks-stack">
        <dt>행동</dt><dd>{{ mutation.data.value.action }}</dd>
        <dt>정책</dt><dd>{{ mutation.data.value.policyId }}</dd>
        <dt>사유</dt><dd>{{ mutation.data.value.reasonCode }}</dd>
        <dt>Lot 매도비율</dt><dd>{{ mutation.data.value.sellRatioOfLot }}</dd>
        <dt>매도 후 종목 비중</dt><dd>{{ mutation.data.value.targetSecurityPortfolioWeightAfter }}</dd>
        <dt>재진입 가능</dt><dd>{{ mutation.data.value.reentryEligible }}</dd>
        <dt>결정 계약</dt><dd>{{ mutation.data.value.decisionContractVersion }}</dd>
        <dt>정책 추적</dt><dd>{{ mutation.data.value.policyTrace.length }}단계</dd>
      </dl>
      <PolicyTracePanel
        v-if="mutation.data.value"
        :entries="mutation.data.value.policyTrace"
        :schema-version="mutation.data.value.policyTraceSchemaVersion"
      />
    </QueryStateBoundary>
  </PageLayout>
</template>
