package control

import (
	"crypto/sha256"
	"encoding/hex"
	"encoding/json"
)

var MonthlyCloudClose = []StepDefinition{
	{Position: 0, Key: "ar_table_ready", Title: "AR Table", Owner: "Finance", Kind: Barrier, Phase: "Input", Description: "确认目标账期 AR Table 已生成，账期与模式明确。", MigratedRuntime: true},
	{Position: 1, Key: "sync_ar_to_bigquery", Title: "Fivetran → BigQuery", Owner: "Fivetran", Kind: Task, Phase: "Input", Description: "绑定或触发精确 connector run，并验证 BigQuery 落地。", DependsOn: []string{"ar_table_ready"}, Scope: []string{"monthly AR connector"}},
	{Position: 2, Key: "verify_billing_inputs", Title: "Billing 输入验证", Owner: "Finance Portal", Kind: Barrier, Phase: "Input", Description: "验证账期、schema、金额与 reference freshness。", DependsOn: []string{"sync_ar_to_bigquery"}, MigratedRuntime: true},
	{Position: 3, Key: "run_monthly_cloud_billing", Title: "Monthly Cloud Billing", Owner: "Finance Portal", Kind: Task, Phase: "Compute", Description: "在 Portal 内运行迁入的月度分配逻辑，生成两张 run-scoped BigQuery 表。", DependsOn: []string{"verify_billing_inputs"}, Scope: []string{"monthly_revrec_collections", "monthly_revrec_orders"}, MigratedRuntime: true},
	{Position: 4, Key: "run_cloud_breakdown", Title: "Cloud Breakdown", Owner: "Finance Portal", Kind: Task, Phase: "Compute", Description: "在 Portal 进程内拆分 Order、RevRec、Collection。", DependsOn: []string{"run_monthly_cloud_billing"}, Scope: []string{"monthly_cloud_order", "monthly_cloud_revrec", "monthly_cloud_collection"}, MigratedRuntime: true},
	{Position: 5, Key: "sync_order_to_crm", Title: "Last Month · Order", Owner: "Finance Portal", Kind: Task, Phase: "Publish", Description: "在 Portal 内创建或更新本月 eligible Order，并读回 OrderItem identity。", DependsOn: []string{"run_cloud_breakdown"}, Scope: []string{"Order", "OrderItem"}, MigratedRuntime: true},
	{Position: 6, Key: "refresh_crm_order_bundle", Title: "CRM Order-only Pipeline", Owner: "Finance Data Pipeline", Kind: Task, Phase: "Publish", Description: "只刷新 Order + OrderItem；禁止全量 CRM Pipeline。Product2 只做 freshness barrier。", DependsOn: []string{"sync_order_to_crm"}, Scope: []string{"nexuscrm_order", "nexuscrm_orderitem"}},
	{Position: 7, Key: "publish_salesforce_order", Title: "Finance Salesforce Order", Owner: "dataplatform_finance", Kind: Task, Phase: "Publish", Description: "只发布 salesforce_order，并验证 Finance TiDB。", DependsOn: []string{"refresh_crm_order_bundle"}, Scope: []string{"salesforce_order"}},
	{Position: 8, Key: "finalize_revrec", Title: "Last Month · RevRec", Owner: "Finance Portal", Kind: Task, Phase: "Finalize", Description: "只更新 RevRec 字段与完成状态，不创建 CRM Revenue。", DependsOn: []string{"publish_salesforce_order"}, Scope: []string{"monthly_cloud_revrec"}, MigratedRuntime: true},
	{Position: 9, Key: "finalize_collection", Title: "Last Month · Collection", Owner: "Finance Portal", Kind: Task, Phase: "Finalize", Description: "更新 Collection 字段和 PDF；不得清空已有 PDF。", DependsOn: []string{"publish_salesforce_order"}, Scope: []string{"monthly_cloud_collection"}, MigratedRuntime: true},
	{Position: 10, Key: "verify_close_complete", Title: "验证出账完成", Owner: "Finance / NetSuite", Kind: Barrier, Phase: "Finalize", Description: "只读验证 Order、RevRec、Collection 与 NetSuite 可见性闭合。", DependsOn: []string{"finalize_revrec", "finalize_collection"}, MigratedRuntime: true},
}

func init() {
	// The v7 prerequisite branches are explicit nodes. Their physical input
	// contracts are intentionally not inferred from the publisher's table order.
	beforeBilling := []StepDefinition{
		{Key: "prepare_crm_references", Title: "输入 CRM 参考数据", Owner: "pingcap-datapipelines", Kind: Barrier, Phase: "Input", Description: "核对明确的源表版本；刷新须使用独立精确范围任务。"},
		{Key: "verify_auxiliary_inputs", Title: "辅助来源与身份检查", Owner: "dbt-dev", Kind: Barrier, Phase: "Input", Description: "检查辅助输入及 registry；身份写操作不属于普通重试。"},
		{Key: "prepare_dbt_billing_inputs", Title: "准备财务模型", Owner: "dbt-dev", Kind: Task, Phase: "Input", DependsOn: []string{"sync_ar_to_bigquery", "prepare_crm_references", "verify_auxiliary_inputs"}},
		{Key: "prepare_finance_org", Title: "生成 Org 前置表", Owner: "dataplatform_finance", Kind: Task, Phase: "Input", Scope: []string{"salesforce_org"}, Description: "显式单表任务；生产者与首个消费者合同待绑定。"},
		{Key: "prepare_finance_account", Title: "生成 Account 前置表", Owner: "dataplatform_finance", Kind: Task, Phase: "Input", Scope: []string{"salesforce_account"}, Description: "显式单表任务；生产者与首个消费者合同待绑定。"},
		{Key: "prepare_finance_order", Title: "生成既有 Order 前置表", Owner: "dataplatform_finance", Kind: Task, Phase: "Input", Scope: []string{"salesforce_order"}, Description: "既有输入版本；不能替代新 Order 同步后的发布版本。"},
	}
	result := []StepDefinition{}
	for _, step := range MonthlyCloudClose {
		if step.Key == "verify_billing_inputs" {
			result = append(result, beforeBilling...)
			step.DependsOn = []string{"prepare_dbt_billing_inputs"}
		}
		if step.Key == "run_monthly_cloud_billing" {
			result = append(result, StepDefinition{Key: "freeze_billing_inputs", Title: "冻结计费输入", Owner: "Finance Portal", Kind: Task, Phase: "Compute", DependsOn: []string{"verify_billing_inputs"}, Description: "物化不可变输入，绑定版本与内容摘要。"})
			step.DependsOn = []string{"freeze_billing_inputs"}
		}
		if step.Key == "publish_salesforce_order" {
			result = append(result, StepDefinition{Key: "verify_publish_references", Title: "发布参考资产检查", Owner: "Finance Portal", Kind: Barrier, Phase: "Publish", DependsOn: []string{"refresh_crm_order_bundle"}})
			step.DependsOn = []string{"verify_publish_references", "prepare_finance_order"}
		}
		if step.Key == "finalize_revrec" {
			result = append(result, StepDefinition{Key: "verify_finance_prerequisites", Title: "验证 Finance 前置表", Owner: "Finance", Kind: Barrier, Phase: "Publish", DependsOn: []string{"prepare_finance_org", "prepare_finance_account", "prepare_finance_order", "publish_salesforce_order"}})
		}
		if step.Key == "finalize_revrec" || step.Key == "finalize_collection" {
			step.DependsOn = []string{"verify_finance_prerequisites"}
		}
		if step.Key == "verify_close_complete" {
			step.Title = "验证出账数据就绪"
		}
		result = append(result, step)
	}
	for i := range result {
		result[i].Position = i
	}
	MonthlyCloudClose = result
}

func DefinitionHash() string {
	payload, _ := json.Marshal(MonthlyCloudClose)
	sum := sha256.Sum256(payload)
	return hex.EncodeToString(sum[:])[:16]
}

func definitionByKey(key string) (StepDefinition, bool) {
	for _, definition := range MonthlyCloudClose {
		if definition.Key == key {
			return definition, true
		}
	}
	return StepDefinition{}, false
}
