#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""市場情報 review_state closeout 後只讀延伸 API。"""

from flask import jsonify, request

from auth import login_required
from routes.market_intel_review_routes import (
    _build_review_decision_writer_receipt_stack,
    _extract_run_payload,
    market_intel_review_bp,
)
from services.market_intel import MarketIntelService
from services.market_intel.candidate_queue_review_ai_summary_preflight import (
    build_candidate_queue_review_ai_summary_preflight,
)
from services.market_intel.candidate_queue_review_ai_summary_output_receipt import (
    build_candidate_queue_review_ai_summary_output_receipt,
)
from services.market_intel.candidate_queue_review_ai_summary_persistence_preflight import (
    build_candidate_queue_review_ai_summary_persistence_preflight,
)
from services.market_intel.candidate_queue_review_ai_summary_persistence_run_package import (
    build_candidate_queue_review_ai_summary_persistence_run_package,
)
from services.market_intel.candidate_queue_review_ai_summary_persistence_transaction import (
    build_candidate_queue_review_ai_summary_persistence_transaction,
)
from services.market_intel.candidate_queue_review_ai_summary_persistence_writer_preflight import (
    build_candidate_queue_review_ai_summary_persistence_writer_preflight,
)
from services.market_intel.candidate_queue_review_ai_summary_run_package import (
    build_candidate_queue_review_ai_summary_run_package,
)
from services.market_intel.candidate_queue_review_archive_summary import (
    build_candidate_queue_review_archive_summary,
)
from services.market_intel.candidate_queue_review_completion_archive import (
    build_candidate_queue_review_completion_archive,
)
from services.market_intel.candidate_queue_review_decision_post_closeout_inventory import (
    build_candidate_queue_review_decision_post_closeout_inventory,
)
from services.market_intel.candidate_queue_review_decision_writer_postwrite_smoke import (
    build_candidate_queue_review_decision_writer_postwrite_smoke,
)
from services.market_intel.candidate_queue_review_decision_writer_run_closeout import (
    build_candidate_queue_review_decision_writer_run_closeout,
)


def _build_post_closeout_inventory_stack(
    *,
    service,
    sample_result,
    payload_error,
    operator_evidence,
    writer_output,
    smoke_result,
    limit,
    execute_requested,
):
    transaction, receipt = _build_review_decision_writer_receipt_stack(
        service=service,
        sample_result=sample_result,
        payload_error=payload_error,
        operator_evidence=operator_evidence,
        writer_output=writer_output,
        postwrite_smoke_result=smoke_result,
        limit=limit,
    )
    closeout = build_candidate_queue_review_decision_writer_run_closeout(
        transaction_preview=transaction,
        run_receipt=receipt,
        operator_evidence=operator_evidence,
    )
    read_only_allowed = bool(execute_requested and closeout.get("closeout_passed"))
    if isinstance(smoke_result, dict) and smoke_result:
        postwrite_smoke = smoke_result
    else:
        postwrite_smoke = build_candidate_queue_review_decision_writer_postwrite_smoke(
            transaction_preview=transaction,
            execute_requested=read_only_allowed,
        )
    inventory = build_candidate_queue_review_decision_post_closeout_inventory(
        transaction_preview=transaction,
        run_closeout=closeout,
        postwrite_smoke=postwrite_smoke,
        live_db_inventory=service.build_live_db_inventory(
            execute_requested=read_only_allowed,
        ),
        operator_evidence=operator_evidence,
        execute_requested=execute_requested,
    )
    return transaction, receipt, closeout, inventory


def _build_review_completion_archive_stack(
    *,
    service,
    sample_result,
    payload_error,
    operator_evidence,
    writer_output,
    smoke_result,
    limit,
    execute_requested,
):
    transaction, receipt, closeout, inventory = _build_post_closeout_inventory_stack(
        service=service,
        sample_result=sample_result,
        payload_error=payload_error,
        operator_evidence=operator_evidence,
        writer_output=writer_output,
        smoke_result=smoke_result,
        limit=limit,
        execute_requested=execute_requested,
    )
    archive = build_candidate_queue_review_completion_archive(
        transaction_preview=transaction,
        run_receipt=receipt,
        run_closeout=closeout,
        post_closeout_inventory=inventory,
        operator_evidence=operator_evidence,
        execute_requested=execute_requested,
    )
    return transaction, receipt, closeout, inventory, archive


def _build_review_archive_summary_stack(
    *,
    service,
    sample_result,
    payload_error,
    operator_evidence,
    writer_output,
    smoke_result,
    limit,
    execute_requested,
):
    transaction, receipt, closeout, inventory, archive = (
        _build_review_completion_archive_stack(
            service=service,
            sample_result=sample_result,
            payload_error=payload_error,
            operator_evidence=operator_evidence,
            writer_output=writer_output,
            smoke_result=smoke_result,
            limit=limit,
            execute_requested=execute_requested,
        )
    )
    archive_summary = build_candidate_queue_review_archive_summary(
        review_completion_archive=archive,
        operator_evidence=operator_evidence,
        execute_requested=execute_requested,
    )
    return transaction, receipt, closeout, inventory, archive, archive_summary


def _build_review_ai_summary_preflight_stack(
    *,
    service,
    sample_result,
    payload_error,
    operator_evidence,
    writer_output,
    smoke_result,
    limit,
    execute_requested,
):
    transaction, receipt, closeout, inventory, archive, archive_summary = (
        _build_review_archive_summary_stack(
            service=service,
            sample_result=sample_result,
            payload_error=payload_error,
            operator_evidence=operator_evidence,
            writer_output=writer_output,
            smoke_result=smoke_result,
            limit=limit,
            execute_requested=execute_requested,
        )
    )
    ai_summary_preflight = build_candidate_queue_review_ai_summary_preflight(
        archive_summary=archive_summary,
        operator_evidence=operator_evidence,
        execute_requested=execute_requested,
    )
    return (
        transaction,
        receipt,
        closeout,
        inventory,
        archive,
        archive_summary,
        ai_summary_preflight,
    )


def _build_review_ai_summary_run_package_stack(
    *,
    service,
    sample_result,
    payload_error,
    operator_evidence,
    writer_output,
    smoke_result,
    limit,
    execute_requested,
):
    (
        transaction,
        receipt,
        closeout,
        inventory,
        archive,
        archive_summary,
        ai_summary_preflight,
    ) = _build_review_ai_summary_preflight_stack(
        service=service,
        sample_result=sample_result,
        payload_error=payload_error,
        operator_evidence=operator_evidence,
        writer_output=writer_output,
        smoke_result=smoke_result,
        limit=limit,
        execute_requested=execute_requested,
    )
    ai_summary_run_package = build_candidate_queue_review_ai_summary_run_package(
        archive_summary=archive_summary,
        ai_summary_preflight=ai_summary_preflight,
        operator_evidence=operator_evidence,
        execute_requested=execute_requested,
    )
    return (
        transaction,
        receipt,
        closeout,
        inventory,
        archive,
        archive_summary,
        ai_summary_preflight,
        ai_summary_run_package,
    )


def _build_review_ai_summary_output_receipt_stack(
    *,
    service,
    sample_result,
    payload_error,
    operator_evidence,
    writer_output,
    smoke_result,
    limit,
    execute_requested,
):
    (
        transaction,
        receipt,
        closeout,
        inventory,
        archive,
        archive_summary,
        ai_summary_preflight,
        ai_summary_run_package,
    ) = _build_review_ai_summary_run_package_stack(
        service=service,
        sample_result=sample_result,
        payload_error=payload_error,
        operator_evidence=operator_evidence,
        writer_output=writer_output,
        smoke_result=smoke_result,
        limit=limit,
        execute_requested=execute_requested,
    )
    ai_summary_output_receipt = build_candidate_queue_review_ai_summary_output_receipt(
        ai_summary_run_package=ai_summary_run_package,
        operator_evidence=operator_evidence,
        execute_requested=execute_requested,
    )
    return (
        transaction,
        receipt,
        closeout,
        inventory,
        archive,
        archive_summary,
        ai_summary_preflight,
        ai_summary_run_package,
        ai_summary_output_receipt,
    )


def _build_review_ai_summary_persistence_preflight_stack(
    *,
    service,
    sample_result,
    payload_error,
    operator_evidence,
    writer_output,
    smoke_result,
    limit,
    execute_requested,
):
    (
        transaction,
        receipt,
        closeout,
        inventory,
        archive,
        archive_summary,
        ai_summary_preflight,
        ai_summary_run_package,
        ai_summary_output_receipt,
    ) = _build_review_ai_summary_output_receipt_stack(
        service=service,
        sample_result=sample_result,
        payload_error=payload_error,
        operator_evidence=operator_evidence,
        writer_output=writer_output,
        smoke_result=smoke_result,
        limit=limit,
        execute_requested=execute_requested,
    )
    ai_summary_persistence_preflight = build_candidate_queue_review_ai_summary_persistence_preflight(
        ai_summary_output_receipt=ai_summary_output_receipt,
        operator_evidence=operator_evidence,
        execute_requested=execute_requested,
    )
    return (
        transaction,
        receipt,
        closeout,
        inventory,
        archive,
        archive_summary,
        ai_summary_preflight,
        ai_summary_run_package,
        ai_summary_output_receipt,
        ai_summary_persistence_preflight,
    )


def _build_review_ai_summary_persistence_transaction_stack(
    *,
    service,
    sample_result,
    payload_error,
    operator_evidence,
    writer_output,
    smoke_result,
    limit,
    execute_requested,
):
    (
        transaction,
        receipt,
        closeout,
        inventory,
        archive,
        archive_summary,
        ai_summary_preflight,
        ai_summary_run_package,
        ai_summary_output_receipt,
        ai_summary_persistence_preflight,
    ) = _build_review_ai_summary_persistence_preflight_stack(
        service=service,
        sample_result=sample_result,
        payload_error=payload_error,
        operator_evidence=operator_evidence,
        writer_output=writer_output,
        smoke_result=smoke_result,
        limit=limit,
        execute_requested=execute_requested,
    )
    ai_summary_persistence_transaction = build_candidate_queue_review_ai_summary_persistence_transaction(
        ai_summary_persistence_preflight=ai_summary_persistence_preflight,
        operator_evidence=operator_evidence,
        execute_requested=execute_requested,
    )
    return (
        transaction,
        receipt,
        closeout,
        inventory,
        archive,
        archive_summary,
        ai_summary_preflight,
        ai_summary_run_package,
        ai_summary_output_receipt,
        ai_summary_persistence_preflight,
        ai_summary_persistence_transaction,
    )


def _build_review_ai_summary_persistence_writer_preflight_stack(
    *,
    service,
    sample_result,
    payload_error,
    operator_evidence,
    writer_output,
    smoke_result,
    limit,
    execute_requested,
    apply_real_write=False,
):
    (
        transaction,
        receipt,
        closeout,
        inventory,
        archive,
        archive_summary,
        ai_summary_preflight,
        ai_summary_run_package,
        ai_summary_output_receipt,
        ai_summary_persistence_preflight,
        ai_summary_persistence_transaction,
    ) = _build_review_ai_summary_persistence_transaction_stack(
        service=service,
        sample_result=sample_result,
        payload_error=payload_error,
        operator_evidence=operator_evidence,
        writer_output=writer_output,
        smoke_result=smoke_result,
        limit=limit,
        execute_requested=execute_requested,
    )
    ai_summary_persistence_writer_preflight = build_candidate_queue_review_ai_summary_persistence_writer_preflight(
        ai_summary_persistence_transaction=ai_summary_persistence_transaction,
        operator_evidence=operator_evidence,
        execute_requested=execute_requested,
        apply_real_write=apply_real_write,
    )
    return (
        transaction,
        receipt,
        closeout,
        inventory,
        archive,
        archive_summary,
        ai_summary_preflight,
        ai_summary_run_package,
        ai_summary_output_receipt,
        ai_summary_persistence_preflight,
        ai_summary_persistence_transaction,
        ai_summary_persistence_writer_preflight,
    )


@market_intel_review_bp.route(
    "/api/market_intel/manual_sample_review/"
    "candidate_queue_review_decision_post_closeout_inventory",
    methods=["POST"],
)
@login_required
def market_intel_manual_sample_candidate_queue_review_decision_post_closeout_inventory():
    service = MarketIntelService()
    execute_requested = request.args.get("execute", "false").lower() == "true"
    sample_result, operator_evidence, writer_output, smoke_result, payload_error, limit = (
        _extract_run_payload()
    )
    transaction, receipt, closeout, inventory = _build_post_closeout_inventory_stack(
        service=service,
        sample_result=sample_result,
        payload_error=payload_error,
        operator_evidence=operator_evidence,
        writer_output=writer_output,
        smoke_result=smoke_result,
        limit=limit,
        execute_requested=execute_requested,
    )
    data = inventory
    data["phase"] = service.phase
    return jsonify(data), 400 if payload_error else 200


@market_intel_review_bp.route(
    "/api/market_intel/manual_sample_review/"
    "candidate_queue_review_archive_summary",
    methods=["POST"],
)
@login_required
def market_intel_manual_sample_candidate_queue_review_archive_summary():
    service = MarketIntelService()
    execute_requested = request.args.get("execute", "false").lower() == "true"
    sample_result, operator_evidence, writer_output, smoke_result, payload_error, limit = (
        _extract_run_payload()
    )
    transaction, receipt, closeout, inventory, archive, archive_summary = (
        _build_review_archive_summary_stack(
            service=service,
            sample_result=sample_result,
            payload_error=payload_error,
            operator_evidence=operator_evidence,
            writer_output=writer_output,
            smoke_result=smoke_result,
            limit=limit,
            execute_requested=execute_requested,
        )
    )
    data = archive_summary
    data["phase"] = service.phase
    return jsonify(data), 400 if payload_error else 200


@market_intel_review_bp.route(
    "/api/market_intel/manual_sample_review/"
    "candidate_queue_review_ai_summary_preflight",
    methods=["POST"],
)
@login_required
def market_intel_manual_sample_candidate_queue_review_ai_summary_preflight():
    service = MarketIntelService()
    execute_requested = request.args.get("execute", "false").lower() == "true"
    sample_result, operator_evidence, writer_output, smoke_result, payload_error, limit = (
        _extract_run_payload()
    )
    (
        transaction,
        receipt,
        closeout,
        inventory,
        archive,
        archive_summary,
        ai_summary_preflight,
    ) = _build_review_ai_summary_preflight_stack(
        service=service,
        sample_result=sample_result,
        payload_error=payload_error,
        operator_evidence=operator_evidence,
        writer_output=writer_output,
        smoke_result=smoke_result,
        limit=limit,
        execute_requested=execute_requested,
    )
    data = ai_summary_preflight
    data["phase"] = service.phase
    return jsonify(data), 400 if payload_error else 200


@market_intel_review_bp.route(
    "/api/market_intel/manual_sample_review/"
    "candidate_queue_review_ai_summary_run_package",
    methods=["POST"],
)
@login_required
def market_intel_manual_sample_candidate_queue_review_ai_summary_run_package():
    service = MarketIntelService()
    execute_requested = request.args.get("execute", "false").lower() == "true"
    sample_result, operator_evidence, writer_output, smoke_result, payload_error, limit = (
        _extract_run_payload()
    )
    (
        transaction,
        receipt,
        closeout,
        inventory,
        archive,
        archive_summary,
        ai_summary_preflight,
        ai_summary_run_package,
    ) = _build_review_ai_summary_run_package_stack(
        service=service,
        sample_result=sample_result,
        payload_error=payload_error,
        operator_evidence=operator_evidence,
        writer_output=writer_output,
        smoke_result=smoke_result,
        limit=limit,
        execute_requested=execute_requested,
    )
    data = ai_summary_run_package
    data["phase"] = service.phase
    return jsonify(data), 400 if payload_error else 200


@market_intel_review_bp.route(
    "/api/market_intel/manual_sample_review/"
    "candidate_queue_review_ai_summary_output_receipt",
    methods=["POST"],
)
@login_required
def market_intel_manual_sample_candidate_queue_review_ai_summary_output_receipt():
    service = MarketIntelService()
    execute_requested = request.args.get("execute", "false").lower() == "true"
    sample_result, operator_evidence, writer_output, smoke_result, payload_error, limit = (
        _extract_run_payload()
    )
    (
        transaction,
        receipt,
        closeout,
        inventory,
        archive,
        archive_summary,
        ai_summary_preflight,
        ai_summary_run_package,
        ai_summary_output_receipt,
    ) = _build_review_ai_summary_output_receipt_stack(
        service=service,
        sample_result=sample_result,
        payload_error=payload_error,
        operator_evidence=operator_evidence,
        writer_output=writer_output,
        smoke_result=smoke_result,
        limit=limit,
        execute_requested=execute_requested,
    )
    data = ai_summary_output_receipt
    data["phase"] = service.phase
    return jsonify(data), 400 if payload_error else 200


@market_intel_review_bp.route(
    "/api/market_intel/manual_sample_review/"
    "candidate_queue_review_ai_summary_persistence_preflight",
    methods=["POST"],
)
@login_required
def market_intel_manual_sample_candidate_queue_review_ai_summary_persistence_preflight():
    service = MarketIntelService()
    execute_requested = request.args.get("execute", "false").lower() == "true"
    sample_result, operator_evidence, writer_output, smoke_result, payload_error, limit = (
        _extract_run_payload()
    )
    (
        transaction,
        receipt,
        closeout,
        inventory,
        archive,
        archive_summary,
        ai_summary_preflight,
        ai_summary_run_package,
        ai_summary_output_receipt,
        ai_summary_persistence_preflight,
    ) = _build_review_ai_summary_persistence_preflight_stack(
        service=service,
        sample_result=sample_result,
        payload_error=payload_error,
        operator_evidence=operator_evidence,
        writer_output=writer_output,
        smoke_result=smoke_result,
        limit=limit,
        execute_requested=execute_requested,
    )
    data = ai_summary_persistence_preflight
    data["phase"] = service.phase
    return jsonify(data), 400 if payload_error else 200


@market_intel_review_bp.route(
    "/api/market_intel/manual_sample_review/"
    "candidate_queue_review_ai_summary_persistence_transaction",
    methods=["POST"],
)
@login_required
def market_intel_manual_sample_candidate_queue_review_ai_summary_persistence_transaction():
    service = MarketIntelService()
    execute_requested = request.args.get("execute", "false").lower() == "true"
    sample_result, operator_evidence, writer_output, smoke_result, payload_error, limit = (
        _extract_run_payload()
    )
    (
        transaction,
        receipt,
        closeout,
        inventory,
        archive,
        archive_summary,
        ai_summary_preflight,
        ai_summary_run_package,
        ai_summary_output_receipt,
        ai_summary_persistence_preflight,
        ai_summary_persistence_transaction,
    ) = _build_review_ai_summary_persistence_transaction_stack(
        service=service,
        sample_result=sample_result,
        payload_error=payload_error,
        operator_evidence=operator_evidence,
        writer_output=writer_output,
        smoke_result=smoke_result,
        limit=limit,
        execute_requested=execute_requested,
    )
    data = ai_summary_persistence_transaction
    data["phase"] = service.phase
    return jsonify(data), 400 if payload_error else 200


@market_intel_review_bp.route(
    "/api/market_intel/manual_sample_review/"
    "candidate_queue_review_ai_summary_persistence_writer_preflight",
    methods=["POST"],
)
@login_required
def market_intel_manual_sample_candidate_queue_review_ai_summary_persistence_writer_preflight():
    service = MarketIntelService()
    execute_requested = request.args.get("execute", "false").lower() == "true"
    apply_real_write = request.args.get("apply_real_write", "false").lower() == "true"
    sample_result, operator_evidence, writer_output, smoke_result, payload_error, limit = (
        _extract_run_payload()
    )
    stack = _build_review_ai_summary_persistence_writer_preflight_stack(
        service=service,
        sample_result=sample_result,
        payload_error=payload_error,
        operator_evidence=operator_evidence,
        writer_output=writer_output,
        smoke_result=smoke_result,
        limit=limit,
        execute_requested=execute_requested,
        apply_real_write=apply_real_write,
    )
    data = stack[-1]
    data["phase"] = service.phase
    return jsonify(data), 400 if payload_error else 200


@market_intel_review_bp.route(
    "/api/market_intel/manual_sample_review/"
    "candidate_queue_review_ai_summary_persistence_run_package",
    methods=["POST"],
)
@login_required
def market_intel_manual_sample_candidate_queue_review_ai_summary_persistence_run_package():
    service = MarketIntelService()
    execute_requested = request.args.get("execute", "false").lower() == "true"
    apply_real_write = request.args.get("apply_real_write", "false").lower() == "true"
    sample_result, operator_evidence, writer_output, smoke_result, payload_error, limit = (
        _extract_run_payload()
    )
    stack = _build_review_ai_summary_persistence_writer_preflight_stack(
        service=service,
        sample_result=sample_result,
        payload_error=payload_error,
        operator_evidence=operator_evidence,
        writer_output=writer_output,
        smoke_result=smoke_result,
        limit=limit,
        execute_requested=execute_requested,
        apply_real_write=apply_real_write,
    )
    data = build_candidate_queue_review_ai_summary_persistence_run_package(
        ai_summary_persistence_writer_preflight=stack[-1],
        operator_evidence=operator_evidence,
        execute_requested=execute_requested,
        apply_real_write=apply_real_write,
    )
    data["phase"] = service.phase
    return jsonify(data), 400 if payload_error else 200


@market_intel_review_bp.route(
    "/api/market_intel/manual_sample_review/"
    "candidate_queue_review_completion_archive",
    methods=["POST"],
)
@login_required
def market_intel_manual_sample_candidate_queue_review_completion_archive():
    service = MarketIntelService()
    execute_requested = request.args.get("execute", "false").lower() == "true"
    sample_result, operator_evidence, writer_output, smoke_result, payload_error, limit = (
        _extract_run_payload()
    )
    transaction, receipt, closeout, inventory, archive = (
        _build_review_completion_archive_stack(
            service=service,
            sample_result=sample_result,
            payload_error=payload_error,
            operator_evidence=operator_evidence,
            writer_output=writer_output,
            smoke_result=smoke_result,
            limit=limit,
            execute_requested=execute_requested,
        )
    )
    data = archive
    data["phase"] = service.phase
    return jsonify(data), 400 if payload_error else 200
