import json
import sys
from pathlib import Path


REQUIRED_FILES = [
    "config/data_quality_rules.json",
    "config/risk_governor_rules.json",
    "config/agent_orchestration_rules.json",
    "config/token_latency_budget.json",
    "config/strategy_rules_v3.json",
    "config/webhook_profiles.json",
    "contracts/ai_trade_plan.schema.json",
    "contracts/signal.schema.json",
    "ops/chat_command_rules.json",
    "ops/release_gates.json",
    "runbooks/incident_playbooks.json",
]

REQUIRED_RUNTIME_FILES = [
    "src/executor.py",
    "src/run_executor.py",
    "src/mt5_adapter.py",
    "src/mt5_live.py",
    "src/ea_bridge_live.py",
    "src/mt5_execution.py",
    "src/incident_engine.py",
    "src/execution_state.py",
    "src/ledger.py",
    "src/tenant_manager.py",
    "src/config_snapshot.py",
    "src/webhook_adapter.py",
    "src/chat_tuning.py",
    "src/control_api.py",
    "src/pipeline.py",
    "deploy/release_manager.py",
    "deploy/install_app.sh",
    "deploy/upgrade_app.sh",
    "deploy/rollback_app.sh",
    "deploy/run_local.sh",
    "deploy/run_stack.sh",
    "deploy/docker-compose.yml",
    "ops/mt5_direct_stress.py",
    "ops/ea_bridge_guide.md",
    "bridge/GoldAutoTradeBridgeEA.mq5",
]


REQUIRED_KEYS = {
    "config/data_quality_rules.json": ["pre_trade_checks", "degrade_policy"],
    "config/risk_governor_rules.json": ["global_limits", "decision_rules"],
    "config/agent_orchestration_rules.json": ["agents", "aggregation_rules", "fallback_rules"],
    "config/token_latency_budget.json": ["token_budget", "latency_sla_ms", "routing_policy"],
    "config/strategy_rules_v3.json": ["trend_vote_model", "entry_rules", "exit_rules"],
    "config/webhook_profiles.json": ["feishu", "qq"],
    "contracts/ai_trade_plan.schema.json": ["required", "properties"],
    "contracts/signal.schema.json": ["required", "properties"],
    "ops/chat_command_rules.json": ["roles", "commands"],
    "ops/release_gates.json": ["promotion_flow", "promotion_gates", "rollback_triggers"],
    "runbooks/incident_playbooks.json": ["severity", "detectors", "auto_actions"],
}


def main() -> int:
    root = Path(__file__).resolve().parents[1]
    errors = []
    for rel in REQUIRED_RUNTIME_FILES:
        path = root / rel
        if not path.exists():
            errors.append(f"missing_runtime_file:{rel}")
    for rel in REQUIRED_FILES:
        path = root / rel
        if not path.exists():
            errors.append(f"missing_file:{rel}")
            continue
        try:
            payload = json.loads(path.read_text(encoding="utf-8"))
        except Exception as exc:
            errors.append(f"invalid_json:{rel}:{exc}")
            continue
        for key in REQUIRED_KEYS.get(rel, []):
            if key not in payload:
                errors.append(f"missing_key:{rel}:{key}")
    if errors:
        print(json.dumps({"ok": False, "errors": errors}, ensure_ascii=False, indent=2))
        return 1
    print(
        json.dumps(
            {"ok": True, "checked_json_files": len(REQUIRED_FILES), "checked_runtime_files": len(REQUIRED_RUNTIME_FILES)},
            ensure_ascii=False,
            indent=2,
        )
    )
    return 0


if __name__ == "__main__":
    sys.exit(main())
