#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""市場情報 MCP run package route extension。"""

from flask import jsonify, request

from auth import login_required
from routes.market_intel_routes import market_intel_bp
from services.market_intel import MarketIntelService
from services.market_intel.mcp_fetch_run_package import (
    build_mcp_fetch_run_package_preview,
)
from services.market_intel.mcp_fetch_run_readiness import (
    build_mcp_fetch_run_readiness_preview,
)


@market_intel_bp.route("/api/market_intel/mcp_fetch_run_package", methods=["GET", "POST"])
@login_required
def market_intel_mcp_fetch_run_package():
    target_review_package = {}
    target_review_result = None
    operator_run_controls = {}
    if request.method == "POST":
        payload = request.get_json(silent=True) or {}
        package = payload.get("run_package") or payload.get("fetch_run_package") or payload
        target_review_package = package.get("target_review_package", {})
        target_review_result = package.get("target_review_result")
        operator_run_controls = package.get("operator_run_controls", {})

    service = MarketIntelService()
    return jsonify(
        build_mcp_fetch_run_package_preview(
            target_review_package=target_review_package,
            target_review_result=target_review_result,
            operator_run_controls=operator_run_controls,
            phase=service.phase,
        )
    )


@market_intel_bp.route("/api/market_intel/mcp_fetch_run_readiness", methods=["GET", "POST"])
@login_required
def market_intel_mcp_fetch_run_readiness():
    run_package = {}
    run_package_result = None
    operator_readiness = {}
    if request.method == "POST":
        payload = request.get_json(silent=True) or {}
        package = payload.get("run_readiness") or payload.get("readiness_package") or payload
        run_package = (
            package.get("run_package")
            or package.get("fetch_run_package")
            or package.get("run_package_payload")
            or {}
        )
        run_package_result = (
            package.get("run_package_result")
            or package.get("mcp_fetch_run_package")
        )
        operator_readiness = (
            package.get("operator_readiness")
            or package.get("operator_run_readiness")
            or {}
        )

    service = MarketIntelService()
    return jsonify(
        build_mcp_fetch_run_readiness_preview(
            run_package=run_package,
            run_package_result=run_package_result,
            operator_readiness=operator_readiness,
            phase=service.phase,
        )
    )
