#!/usr/bin/env python3
"""Run a non-destructive Elasticsearch component snapshot/restore drill.

Run from the repository root: python3 lab/snapshot-drill.py
Requires this lab's running Elasticsearch service and path.repo=/snapshots.
Only the dedicated sectools-drill-* data and repository registration are written.
No platform index, snapshot, or volume is deleted; no service is stopped.
This is NOT a complete OpenCTI backup or disaster-recovery test.
"""

import datetime
import json
from pathlib import Path
import subprocess
import sys
import uuid

LAB_DIR = Path(__file__).resolve().parent
SOURCE_INDEX = "sectools-drill-source"
REPOSITORY = "sectools-lab-snapshots"
LOCATION = "/snapshots"
DOCUMENT_ID = "marker"
OWNERSHIP_MARKER = "sectools-snapshot-drill-v1"
DOCUMENT = {
    "dataset": "SecTools Lab",
    "purpose": "Elasticsearch component snapshot and restore drill only",
    "marker": "snapshot-roundtrip-v1",
}


class DrillError(Exception):
    """A failed check; existing drill artifacts are deliberately retained."""


def api(method, path, payload=None, allow_missing=False, timeout=180):
    """Call ES locally through Docker; pass JSON on stdin and return parsed JSON."""
    command = [
        "docker", "compose", "exec", "-T", "elasticsearch",
        "curl", "-fsS", "--connect-timeout", "10", "--max-time", str(timeout),
        "--request", method, "--write-out", "\n%{http_code}",
        "--header", "Content-Type: application/json",
    ]
    if payload is not None:
        command.extend(["--data-binary", "@-"])
    command.append("http://localhost:9200" + path)
    try:
        completed = subprocess.run(
            command,
            input=json.dumps(payload) if payload is not None else None,
            text=True,
            stdout=subprocess.PIPE,
            stderr=subprocess.PIPE,
            cwd=LAB_DIR,
            timeout=timeout + 20,
            check=False,
        )
    except FileNotFoundError as exc:
        raise DrillError("找不到 Docker CLI，請先完成 Docker 安裝。") from exc
    except subprocess.TimeoutExpired as exc:
        raise DrillError(
            f"{method} {path} 超過等待期限；工作可能仍在 Elasticsearch 執行。"
            "請先檢查本次快照或還原狀態，不要直接當成未執行而重送。"
        ) from exc

    body, separator, status_text = completed.stdout.rpartition("\n")
    status = int(status_text) if separator and status_text.isdigit() else 0
    if allow_missing and method == "GET" and status == 404 and completed.returncode == 22:
        return None
    if completed.returncode or not 200 <= status < 300:
        detail = completed.stderr.strip()[-800:] or "未取得成功的 HTTP 回應"
        raise DrillError(
            f"{method} {path} 失敗（HTTP {status or 'unknown'}, exit {completed.returncode}）：{detail}"
            "；若是等待逾時，伺服器作業可能仍在執行。"
        )
    try:
        result = json.loads(body)
    except (ValueError, TypeError) as exc:
        raise DrillError(f"{method} {path} 回傳非有效 JSON。") from exc
    if not isinstance(result, dict):
        raise DrillError(f"{method} {path} 回傳非預期的 JSON 型別。")
    if result.get("error") or result.get("errors"):
        raise DrillError(f"{method} {path} 回傳 Elasticsearch 錯誤，未通過驗證。")
    return result


def require(condition, message):
    if not condition:
        raise DrillError(message)


def verify_one_document(index):
    result = api("GET", f"/{index}/_doc/{DOCUMENT_ID}")
    require(result.get("found") is True, f"{index} 找不到標記文件。")
    require(result.get("_source") == DOCUMENT, f"{index} 的文件內容與預期不符。")
    count = api("GET", f"/{index}/_count")
    require(count.get("count") == 1, f"{index} 不是恰好一筆教學文件，停止演練。")
    require(count.get("_shards", {}).get("failed") == 0, f"{index} 的計數查詢有失敗分片。")


def main():
    timestamp = datetime.datetime.now(datetime.timezone.utc).strftime("%Y%m%d-%H%M%S-%f")
    run_id = timestamp + "-" + uuid.uuid4().hex[:8]
    snapshot = "sectools-drill-" + run_id
    restored_index = "sectools-drill-restored-" + run_id
    print("SecTools Lab｜Elasticsearch 元件 Snapshot / Restore 演練", flush=True)
    print("範圍：單一獨立教學索引；不包含 OpenCTI 平台資料、附件或完整災難復原。", flush=True)
    print("行為：建立／保留教學索引、快照與新還原索引；不刪除資料、不停止服務。", flush=True)
    print(f"SNAPSHOT={snapshot}\nRESTORED_INDEX={restored_index}", flush=True)

    existing = api("GET", f"/{SOURCE_INDEX}", allow_missing=True)
    if existing is None:
        result = api("PUT", f"/{SOURCE_INDEX}", {
            "settings": {"number_of_shards": 1, "number_of_replicas": 0},
            "mappings": {
                "_meta": {"sectools_snapshot_drill": OWNERSHIP_MARKER},
                "properties": {
                    "dataset": {"type": "keyword"},
                    "purpose": {"type": "keyword"},
                    "marker": {"type": "keyword"},
                },
            },
        })
        require(result.get("acknowledged") is True, "教學索引建立未獲確認。")
    else:
        metadata = existing.get(SOURCE_INDEX, {}).get("mappings", {}).get("_meta", {})
        require(
            metadata.get("sectools_snapshot_drill") == OWNERSHIP_MARKER,
            "同名來源索引已存在但沒有本腳本的所有權標記；為避免修改其他資料，已停止。",
        )

    marker = api("GET", f"/{SOURCE_INDEX}/_doc/{DOCUMENT_ID}", allow_missing=True)
    if marker is None:
        count = api("GET", f"/{SOURCE_INDEX}/_count")
        require(count.get("count") == 0, "來源索引已有其他文件；不覆寫、不清空。")
        created = api("PUT", f"/{SOURCE_INDEX}/_create/{DOCUMENT_ID}?refresh=wait_for", DOCUMENT)
        require(created.get("result") == "created", "教學標記文件建立未獲確認。")
    verify_one_document(SOURCE_INDEX)
    print("PASS｜來源索引僅含一筆已核對的教學標記文件。", flush=True)

    repository = api("GET", f"/_snapshot/{REPOSITORY}", allow_missing=True)
    if repository is None:
        registered = api("PUT", f"/_snapshot/{REPOSITORY}?verify=true", {
            "type": "fs", "settings": {"location": LOCATION, "compress": True},
        })
        require(registered.get("acknowledged") is True, "Snapshot 儲存庫註冊未獲確認。")
    else:
        config = repository.get(REPOSITORY, {})
        settings = config.get("settings", {})
        require(
            config.get("type") == "fs"
            and settings.get("location") == LOCATION
            and settings.get("readonly", False) in (False, "false"),
            "同名 Snapshot 儲存庫的設定與教學環境不同；不覆寫既有設定。",
        )
    verification = api("POST", f"/_snapshot/{REPOSITORY}/_verify")
    require(bool(verification.get("nodes")), "Snapshot 儲存庫驗證未回報可用節點。")
    print("PASS｜fs 儲存庫 /snapshots 已註冊且可用。", flush=True)

    result = api("PUT", f"/_snapshot/{REPOSITORY}/{snapshot}?wait_for_completion=true", {
        "indices": SOURCE_INDEX,
        "ignore_unavailable": False,
        "include_global_state": False,
        "feature_states": ["none"],
        "metadata": {"purpose": OWNERSHIP_MARKER, "run_id": run_id},
    })
    captured = result.get("snapshot", {})
    require(captured.get("state") == "SUCCESS", "Snapshot 未達到 SUCCESS。")
    require(captured.get("indices") == [SOURCE_INDEX], "Snapshot 索引範圍與預期不符。")
    require(captured.get("shards", {}).get("failed") == 0, "Snapshot 包含失敗分片。")
    print("PASS｜Snapshot SUCCESS；只包含教學索引，未包含 global state。", flush=True)

    require(
        api("GET", f"/{restored_index}", allow_missing=True) is None,
        "還原目標索引已存在，停止以避免影響既有資料。",
    )
    result = api("POST", f"/_snapshot/{REPOSITORY}/{snapshot}/_restore?wait_for_completion=true", {
        "indices": SOURCE_INDEX,
        "include_global_state": False,
        "include_aliases": False,
        "feature_states": ["none"],
        "rename_pattern": "^" + SOURCE_INDEX + "$",
        "rename_replacement": restored_index,
    })
    restored = result.get("snapshot", {})
    shards = restored.get("shards", {})
    require(restored.get("indices") == [restored_index], "Restore 回報的目標索引與預期不符。")
    require(
        shards.get("failed") == 0
        and shards.get("total", 0) > 0
        and shards.get("successful") == shards.get("total"),
        "Restore 分片未全部成功。",
    )
    api("POST", f"/{restored_index}/_refresh")
    verify_one_document(restored_index)
    print("PASS｜已還原至全新索引；文件內容完全相同，文件數為 1。", flush=True)
    print("PASS｜Elasticsearch 元件還原演練完成。", flush=True)
    print("驗證邊界：沒有驗證 OpenCTI 索引、S3 附件、帳號權限、跨版本相容性或整套 DR。", flush=True)
    print("所有教學索引與快照均保留；相同主機的具名 Volume 不是異地備份。", flush=True)


if __name__ == "__main__":
    try:
        main()
    except (DrillError, KeyboardInterrupt) as exc:
        message = str(exc) or "操作已中斷；伺服器端工作可能仍在執行。"
        print(f"FAIL｜{message}", file=sys.stderr)
        print("未刪除任何索引或快照。請保留上述識別碼，檢查實際狀態後再決定下一步。", file=sys.stderr)
        sys.exit(1)
