///|
pub(all) struct AnalysisWorkspaceInput {
  run_id : @domain.RunId
  operator_request : String
  data_source : @domain.DataSource
  symbol : @domain.Symbol
  timeframe : @domain.Timeframe
  limit : Int
  captured_at_ms : Int64
  suite_status : @model.SuiteStatusRef
  diagnosis : @domain.Stage1Diagnosis
  decision : @domain.Stage2Decision
} derive(Debug, Eq, ToJson, FromJson)

///|
pub(all) struct AnalysisWorkspace {
  plan : @planning.AnalysisPlan
  bundle : @workflow.AnalysisRunBundle
  routine_result : @orchestration.TwoStageRoutineResult?
  job_state : @job.AnalysisJobState
  retry_decision : @retry.RetryDecision
  decision_policy : @policy.DecisionPolicyReport
  run_view : @app.OperatorRunView
  app_tool_manifest : @app.MoondeskAppToolManifest
  replay_plan : @replay.ReplayPlan
  export_manifest : @export.ExportManifest
  safety_report : @safety.SafetyReport
  history : @history.RunHistoryIndex
  manifest_tool_count : Int
  chart_candle_count : Int
  book_artifact_count : Int
  summary : String
} derive(Debug, Eq, ToJson, FromJson)

///|
pub fn analysis_workspace_input(
  run_id : @domain.RunId,
  operator_request : String,
  data_source : @domain.DataSource,
  symbol : @domain.Symbol,
  timeframe : @domain.Timeframe,
  suite_status : @model.SuiteStatusRef,
  diagnosis : @domain.Stage1Diagnosis,
  decision : @domain.Stage2Decision,
  limit? : Int = 60,
  captured_at_ms? : Int64 = 0L,
) -> AnalysisWorkspaceInput {
  {
    run_id,
    operator_request,
    data_source,
    symbol,
    timeframe,
    limit,
    captured_at_ms,
    suite_status,
    diagnosis,
    decision,
  }
}

///|
fn stage1_validation_report(
  bundle : @workflow.AnalysisRunBundle,
) -> @domain.ValidationReport {
  match bundle.projection {
    Some(projection) =>
      if projection.result.record.validation.length() > 0 {
        projection.result.record.validation[0]
      } else {
        @domain.validation_ok()
      }
    None => @domain.validation_ok()
  }
}

///|
fn chart_candle_count(bundle : @workflow.AnalysisRunBundle) -> Int {
  match bundle.chart_frame {
    Some(frame) => frame.candles.length()
    None => 0
  }
}

///|
fn book_artifact_count(bundle : @workflow.AnalysisRunBundle) -> Int {
  match bundle.write_plan {
    Some(plan) => plan.artifacts.length()
    None => 0
  }
}

///|
fn projected_event_count(bundle : @workflow.AnalysisRunBundle) -> Int {
  match bundle.projection {
    Some(projection) => projection.result.events.length()
    None => 0
  }
}

///|
fn projected_phase_count(bundle : @workflow.AnalysisRunBundle) -> Int {
  match bundle.projection {
    Some(projection) => projection.result.plan.phases.length()
    None => 0
  }
}

///|
fn projected_prompt_schema(bundle : @workflow.AnalysisRunBundle) -> String {
  match bundle.projection {
    Some(projection) => projection.stage1_prompt.schema_id
    None => "none"
  }
}

///|
fn projected_model(bundle : @workflow.AnalysisRunBundle) -> String {
  match bundle.projection {
    Some(projection) => projection.stage1_model_request.model
    None => bundle.request.gateway.default_model
  }
}

///|
fn routine_result_for_bundle(
  bundle : @workflow.AnalysisRunBundle,
) -> @orchestration.TwoStageRoutineResult? {
  match bundle.market_fetch.snapshot {
    Some(snapshot) =>
      Some(
        @orchestration.run_two_stage_routine(
          @orchestration.two_stage_routine_input(
            @routine.routine_request(
              bundle.request.run_id,
              bundle.request.operator_request,
              snapshot,
            ),
            bundle.request.gateway,
            bundle.request.diagnosis,
            bundle.request.decision,
          ),
        ),
      )
    None => None
  }
}

///|
fn routine_summary(result : @orchestration.TwoStageRoutineResult?) -> String {
  match result {
    Some(routine_result) => routine_result.summary
    None => "two-stage routine awaits market evidence"
  }
}

///|
fn workspace_summary(workspace : AnalysisWorkspace, adapter : String) -> String {
  "moonfish planned \{projected_phase_count(workspace.bundle)} phases, \{projected_event_count(workspace.bundle)} projected events, \{workspace.book_artifact_count} book artifacts, \{workspace.chart_candle_count} chart candles, \{workspace.run_view.review_count} review items, \{workspace.run_view.followup_topic_count} follow-up topics, \{workspace.run_view.panels.length()} app panels, \{workspace.app_tool_manifest.surfaces.length()} app-tool surfaces, \{workspace.replay_plan.steps.length()} replay steps, \{workspace.export_manifest.item_count} export items, \{workspace.safety_report.findings.length()} safety checks, \{workspace.history.total_count} history rows, a \{projected_prompt_schema(workspace.bundle)} prompt, and a \{projected_model(workspace.bundle)} model call for \{workspace.bundle.request.market.symbol} via \{adapter}; plan is \{workspace.plan.summary}; job is \{workspace.job_state.outcome.label()}; retry is \{workspace.retry_decision.issue_class.label()}; orchestration is \{routine_summary(workspace.routine_result)}; app-tool is \{workspace.app_tool_manifest.summary}; pack has \{workspace.manifest_tool_count} tools"
}

///|
pub fn prepare_analysis_workspace(
  input : AnalysisWorkspaceInput,
) -> AnalysisWorkspace {
  let plan = @planning.prepare_analysis_plan(
    @planning.analysis_plan_input(
      input.run_id,
      input.operator_request,
      input.data_source,
      input.symbol,
      input.timeframe,
      input.suite_status,
      limit=input.limit,
      captured_at_ms=input.captured_at_ms,
    ),
  )
  let bundle = @workflow.run_analysis_bundle(
    @workflow.analysis_run_request(
      input.run_id,
      input.operator_request,
      @data.market_source_request(
        input.data_source,
        input.symbol,
        input.timeframe,
        limit=input.limit,
        captured_at_ms=input.captured_at_ms,
      ),
      plan.gateway,
      input.diagnosis,
      input.decision,
    ),
  )
  let job_state = @job.prepare_analysis_job(
    @job.analysis_job_input(plan, bundle~),
  )
  let routine_result = routine_result_for_bundle(bundle)
  let retry_decision = @retry.prepare_retry_decision(
    @retry.retry_decision_input(Stage1, stage1_validation_report(bundle)),
  )
  let decision_policy = @policy.evaluate_decision_policy(
    @policy.decision_policy_input(input.run_id, input.diagnosis, input.decision),
  )
  let run_view = @app.operator_run_view(bundle)
  let app_tool_manifest = @app.moondesk_app_tool_manifest(run_view)
  let replay_plan = @replay.prepare_replay_plan(bundle)
  let export_manifest = @export.prepare_export_manifest(bundle)
  let safety_report = @safety.prepare_safety_report(bundle)
  let history = @history.render_run_history(
    @history.run_history_input([bundle]),
  )
  let workspace : AnalysisWorkspace = {
    plan,
    bundle,
    routine_result,
    job_state,
    retry_decision,
    decision_policy,
    run_view,
    app_tool_manifest,
    replay_plan,
    export_manifest,
    safety_report,
    history,
    manifest_tool_count: @pack.price_action_manifest().tools.length(),
    chart_candle_count: chart_candle_count(bundle),
    book_artifact_count: book_artifact_count(bundle),
    summary: "",
  }
  {
    ..workspace,
    summary: workspace_summary(workspace, bundle.market_fetch.plan.adapter),
  }
}