from __future__ import annotations

import argparse
import ctypes
from datetime import datetime, timezone
import json
import os
from pathlib import Path
import platform
import re
import shutil
import statistics
import subprocess
import sys
from time import perf_counter
import uuid


PROJECT_ROOT = Path(__file__).resolve().parents[1]
if str(PROJECT_ROOT) not in sys.path:
    sys.path.insert(0, str(PROJECT_ROOT))

from scripts.benchmark_solver_scale import LAB_PROFILES


PROFILE_ORDER = tuple(LAB_PROFILES)


def _total_memory_bytes() -> int | None:
    if os.name == "nt":
        class MemoryStatusEx(ctypes.Structure):
            _fields_ = [
                ("dwLength", ctypes.c_ulong),
                ("dwMemoryLoad", ctypes.c_ulong),
                ("ullTotalPhys", ctypes.c_ulonglong),
                ("ullAvailPhys", ctypes.c_ulonglong),
                ("ullTotalPageFile", ctypes.c_ulonglong),
                ("ullAvailPageFile", ctypes.c_ulonglong),
                ("ullTotalVirtual", ctypes.c_ulonglong),
                ("ullAvailVirtual", ctypes.c_ulonglong),
                ("ullAvailExtendedVirtual", ctypes.c_ulonglong),
            ]

        status = MemoryStatusEx()
        status.dwLength = ctypes.sizeof(status)
        if ctypes.windll.kernel32.GlobalMemoryStatusEx(ctypes.byref(status)):
            return int(status.ullTotalPhys)
        return None
    try:
        return int(os.sysconf("SC_PAGE_SIZE") * os.sysconf("SC_PHYS_PAGES"))
    except (AttributeError, OSError, ValueError):
        return None


def _resolve_node(requested: str | None) -> Path:
    candidates: list[Path] = []
    if requested:
        candidates.append(Path(requested))
    configured = os.getenv("FSE3D_NODE", "").strip()
    if configured:
        candidates.append(Path(configured))
    if os.name == "nt":
        program_files = os.getenv("ProgramFiles", r"C:\Program Files")
        candidates.append(Path(program_files) / "nodejs" / "node.exe")
    discovered = shutil.which("node")
    if discovered:
        candidates.append(Path(discovered))
    for candidate in candidates:
        if candidate.is_file():
            return candidate.resolve()
    raise RuntimeError("Node.js nao encontrado para o laboratorio.")


def _resolve_npm(node: Path) -> Path:
    candidate = node.with_name("npm.cmd" if os.name == "nt" else "npm")
    if candidate.is_file():
        return candidate.resolve()
    discovered = shutil.which("npm")
    if discovered:
        return Path(discovered).resolve()
    raise RuntimeError("npm nao encontrado para o laboratorio.")


def _run_command(
    label: str,
    command: list[str],
    *,
    timeout_seconds: int,
    environment: dict[str, str] | None = None,
) -> dict[str, object]:
    print(f"==> {label}", flush=True)
    started = perf_counter()
    try:
        completed = subprocess.run(
            command,
            cwd=PROJECT_ROOT,
            text=True,
            stdout=subprocess.PIPE,
            stderr=subprocess.STDOUT,
            check=False,
            timeout=timeout_seconds,
            env=environment,
            creationflags=(
                getattr(subprocess, "CREATE_NO_WINDOW", 0)
                if os.name == "nt"
                else 0
            ),
        )
        output = completed.stdout or ""
        record: dict[str, object] = {
            "label": label,
            "command": command,
            "returncode": completed.returncode,
            "duration_seconds": round(perf_counter() - started, 6),
            "output_tail": output.splitlines()[-40:],
            "ok": completed.returncode == 0,
        }
        unittest_count = re.search(r"Ran (\d+) tests?", output)
        pytest_count = re.search(r"(?:^|\s)(\d+) passed(?:,|\s|$)", output)
        subtest_count = re.search(r"(?:^|\s)(\d+) subtests passed(?:,|\s|$)", output)
        if pytest_count:
            record["test_count"] = int(pytest_count.group(1))
        elif unittest_count:
            record["test_count"] = int(unittest_count.group(1))
        if subtest_count:
            record["subtest_count"] = int(subtest_count.group(1))
        return record
    except subprocess.TimeoutExpired as exc:
        output = (exc.stdout or "") if isinstance(exc.stdout, str) else ""
        return {
            "label": label,
            "command": command,
            "returncode": None,
            "duration_seconds": round(perf_counter() - started, 6),
            "output_tail": output.splitlines()[-40:],
            "ok": False,
            "error": f"timeout apos {timeout_seconds} s",
        }


def _read_json(path: Path) -> dict[str, object]:
    return json.loads(path.read_text(encoding="utf-8"))


def _read_command_json(
    result: dict[str, object],
    output: Path,
) -> dict[str, object] | None:
    if not result["ok"]:
        return None
    if not output.is_file():
        result["ok"] = False
        result["error"] = f"arquivo de metricas nao foi criado: {output}"
        return None
    try:
        return _read_json(output)
    except (OSError, ValueError, TypeError) as exc:
        result["ok"] = False
        result["error"] = f"arquivo de metricas invalido: {exc}"
        return None


def _write_atomic(path: Path, content: str) -> None:
    path.parent.mkdir(parents=True, exist_ok=True)
    temporary = path.with_name(f".{path.name}.{uuid.uuid4().hex}.tmp")
    try:
        temporary.write_text(content, encoding="utf-8")
        os.replace(temporary, path)
    finally:
        temporary.unlink(missing_ok=True)


def _median(runs: list[dict[str, object]], key: str) -> float | None:
    values = [float(run[key]) for run in runs if run.get(key) is not None]
    return statistics.median(values) if values else None


def _maximum(runs: list[dict[str, object]], key: str) -> float | None:
    values = [float(run[key]) for run in runs if run.get(key) is not None]
    return max(values) if values else None


def _human_bytes(value: float | int | None) -> str:
    if value is None:
        return "n/d"
    number = float(value)
    for unit in ("B", "KB", "MB", "GB", "TB"):
        if abs(number) < 1024.0 or unit == "TB":
            return f"{number:.2f} {unit}"
        number /= 1024.0
    return f"{number:.2f} TB"


def _seconds(value: float | None) -> str:
    return "n/d" if value is None else f"{value:.3f} s"


def _milliseconds(value: float | None) -> str:
    return "n/d" if value is None else f"{value:.2f} ms"


def _hardware_info(node: Path) -> dict[str, object]:
    try:
        import openseespy.opensees as ops

        opensees_version = str(ops.version())
    except Exception:
        opensees_version = "indisponivel"
    revision_path = PROJECT_ROOT / "frontend" / "revision.json"
    try:
        revision = json.loads(revision_path.read_text(encoding="utf-8")).get("revision")
    except (OSError, ValueError, TypeError):
        revision = "desconhecida"
    return {
        "revision": revision,
        "platform": platform.platform(),
        "processor": os.getenv("PROCESSOR_IDENTIFIER") or platform.processor() or "desconhecido",
        "logical_cpus": os.cpu_count(),
        "total_memory_bytes": _total_memory_bytes(),
        "python": sys.version.split()[0],
        "python_executable": sys.executable,
        "node_executable": str(node),
        "openseespy": opensees_version,
    }


def _run_test_stages(
    node: Path,
    npm: Path,
    *,
    stress_iterations: int,
) -> list[dict[str, object]]:
    runtime_dir = PROJECT_ROOT / "tmp" / "reliability" / "runtime"
    runtime_dir.mkdir(parents=True, exist_ok=True)
    rate_limit_path = runtime_dir / f"rate-limit-{uuid.uuid4().hex}.sqlite3"
    test_environment = os.environ.copy()
    test_environment["FSE3D_RATE_LIMIT_DB_PATH"] = str(rate_limit_path)

    stages = [
        _run_command(
            "TypeScript build",
            [str(npm), "run", "check:frontend"],
            timeout_seconds=300,
        ),
        _run_command(
            "Python unit and integration tests",
            [
                sys.executable,
                "-W",
                "ignore::DeprecationWarning",
                "-m",
                "pytest",
                "-q",
                "tests",
            ],
            timeout_seconds=600,
            environment=test_environment,
        ),
        _run_command(
            "Repeated concurrency and numerical stress",
            [
                sys.executable,
                str(PROJECT_ROOT / "scripts" / "stress_reliability.py"),
                "--iterations",
                str(stress_iterations),
            ],
            timeout_seconds=900,
        ),
    ]
    for test_path in sorted((PROJECT_ROOT / "tests").glob("frontend_*.mjs")):
        stages.append(
            _run_command(
                f"Frontend test {test_path.name}",
                [str(node), "--no-warnings", str(test_path.relative_to(PROJECT_ROOT))],
                timeout_seconds=180,
            )
        )
    for suffix in ("", "-wal", "-shm"):
        rate_limit_path.with_name(rate_limit_path.name + suffix).unlink(missing_ok=True)
    return stages


def _benchmark_solver_profile(
    profile_name: str,
    *,
    mode: str,
    repetitions: int,
    max_elements: int,
    run_dir: Path,
) -> tuple[list[dict[str, object]], list[dict[str, object]]]:
    metrics: list[dict[str, object]] = []
    commands: list[dict[str, object]] = []
    for repetition in range(1, repetitions + 1):
        output = run_dir / f"{profile_name}-{mode}-{repetition}.json"
        command = [
            sys.executable,
            str(PROJECT_ROOT / "scripts" / "benchmark_solver_scale.py"),
            "--profile",
            profile_name,
            "--mode",
            mode,
            "--diagram-points",
            "21",
            "--solver-element-guard",
            str(max_elements),
            "--output",
            str(output),
        ]
        result = _run_command(
            f"Solver {profile_name} {mode} rodada {repetition}/{repetitions}",
            command,
            timeout_seconds=1_800,
        )
        commands.append(result)
        run_metrics = _read_command_json(result, output)
        if run_metrics is not None:
            metrics.append(run_metrics)
    return metrics, commands


def _benchmark_frontend(
    node: Path,
    element_count: int,
    run_dir: Path,
) -> tuple[dict[str, object] | None, dict[str, object]]:
    output = run_dir / f"frontend-{element_count}.json"
    command = [
        str(node),
        "--no-warnings",
        str(PROJECT_ROOT / "scripts" / "benchmark_frontend_model.mjs"),
        "--elements",
        str(element_count),
        "--output",
        str(output),
    ]
    result = _run_command(
        f"Frontend {element_count} barras",
        command,
        timeout_seconds=300,
    )
    return (_read_command_json(result, output), result)


def _render_markdown(report: dict[str, object]) -> str:
    hardware = report["hardware"]
    test_stages = report["tests"]
    direct = report["solver_direct"]
    pipeline = report["solver_pipeline"]
    frontend = report["frontend"]
    failures = report["failures"]
    lines = [
        "# Relatorio automatico de confiabilidade FSE3D",
        "",
        f"- Gerado em UTC: `{report['generated_at']}`.",
        f"- Revisao: `{hardware['revision']}`.",
        f"- Resultado geral: **{'APROVADO' if report['ok'] else 'FALHOU'}**.",
        f"- Duracao total: `{_seconds(report['duration_seconds'])}`.",
        "",
        "## Ambiente",
        "",
        f"- Processador: `{hardware['processor']}`.",
        f"- CPUs logicas: `{hardware['logical_cpus']}`.",
        f"- Memoria fisica: `{_human_bytes(hardware['total_memory_bytes'])}`.",
        f"- Python: `{hardware['python']}`.",
        f"- OpenSeesPy: `{hardware['openseespy']}`.",
        f"- Plataforma: `{hardware['platform']}`.",
        "",
        "## Testes automatizados",
        "",
        "| Etapa | Estado | Duracao |",
        "| --- | --- | ---: |",
    ]
    for stage in test_stages:
        stage_label = str(stage["label"])
        count_labels: list[str] = []
        if stage.get("test_count") is not None:
            count_labels.append(f"{stage['test_count']} testes")
        if stage.get("subtest_count") is not None:
            count_labels.append(f"{stage['subtest_count']} subtestes")
        if count_labels:
            stage_label += f" ({', '.join(count_labels)})"
        lines.append(
            f"| {stage_label} | {'OK' if stage['ok'] else 'FALHOU'} | "
            f"{_seconds(float(stage['duration_seconds']))} |"
        )

    lines.extend([
        "",
        "## Solver direto",
        "",
        "Cada rodada usa um processo novo, evitando que memoria de um porte contamine o seguinte.",
        "",
        "| Alvo | Nos | Barras | Classe | Rodadas | Solver mediano | Pico maximo | Entrada JSON | Resposta JSON | Detalhe | Integridade |",
        "| --- | ---: | ---: | --- | ---: | ---: | ---: | ---: | ---: | --- | --- |",
    ])
    for entry in direct:
        lines.append(
            f"| {entry['profile']} | {entry['nodes']:,} | {entry['elements']:,} | "
            f"{entry['scale']} | {entry['run_count']} | {_seconds(entry['solve_seconds_median'])} | "
            f"{_human_bytes(entry['peak_working_set_max_bytes'])} | "
            f"{_human_bytes(entry['request_json_bytes_median'])} | "
            f"{_human_bytes(entry['response_json_bytes_median'])} | {entry['result_detail']} | "
            f"{'OK' if entry['integrity_ok'] else 'FALHOU'} |"
        )

    lines.extend([
        "",
        "## Caminho isolado de artefatos",
        "",
        "Inclui compressao da entrada, subprocesso, manifesto, hash, descompactacao e validacao da resposta.",
        "",
        "| Alvo | Barras | Tempo do worker | Solver informado | Entrada comprimida | Resultado comprimido | Artefatos |",
        "| --- | ---: | ---: | ---: | ---: | ---: | --- |",
    ])
    for entry in pipeline:
        lines.append(
            f"| {entry['profile']} | {entry['elements']:,} | "
            f"{_seconds(entry['pipeline_worker_seconds_median'])} | "
            f"{_seconds(entry['solver_reported_seconds_median'])} | "
            f"{_human_bytes(entry['request_artifact_bytes_median'])} | "
            f"{_human_bytes(entry['response_artifact_bytes_median'])} | "
            f"{'OK' if entry['hashes_ok'] and entry['integrity_ok'] else 'FALHOU'} |"
        )

    lines.extend([
        "",
        "## Preparacao no frontend",
        "",
        "| Barras | Validacao | Serializacao | Clone JSON | Pico observado | JSON | Erros |",
        "| ---: | ---: | ---: | ---: | ---: | ---: | ---: |",
    ])
    for entry in frontend:
        lines.append(
            f"| {entry['elements']:,} | {_milliseconds(entry['validation_milliseconds'])} | "
            f"{_milliseconds(entry['serialize_milliseconds'])} | "
            f"{_milliseconds(entry['parse_clone_milliseconds'])} | "
            f"{_human_bytes(entry['peak_observed_rss_bytes'])} | "
            f"{_human_bytes(entry['serialized_bytes'])} | {entry['validation_errors']} |"
        )

    max_solved = max((entry["elements"] for entry in direct), default=0)
    lines.extend([
        "",
        "## Leitura tecnica",
        "",
        f"- Maior modelo resolvido nesta execucao: `{max_solved:,}` barras.",
        "- Os modelos de escala sao porticos espaciais sinteticos, regulares e estaveis.",
        "- A geometria regular comprime muito bem; os tamanhos gzip nao devem ser usados sozinhos para dimensionar rede e armazenamento de modelos reais.",
        "- O resultado mede esta maquina e esta revisao; nao constitui garantia universal para qualquer topologia.",
        "- Tempos de fila de infraestrutura comercial nao fazem parte do solver direto.",
        "- Mudancas futuras devem comparar um novo relatorio com este marco, sem transformar tempo absoluto em teste fragil.",
    ])
    if failures:
        lines.extend(["", "## Falhas", ""])
        for failure in failures:
            lines.append(f"- `{failure}`")
    lines.append("")
    return "\n".join(lines)


def parse_args() -> argparse.Namespace:
    parser = argparse.ArgumentParser(
        description="Executa a bancada automatica de confiabilidade e escala do FSE3D.",
    )
    parser.add_argument("--level", choices=("quick", "full"), default="quick")
    parser.add_argument("--max-solve-elements", type=int)
    parser.add_argument("--output-dir", type=Path, default=PROJECT_ROOT / "tmp" / "reliability")
    parser.add_argument("--node")
    parser.add_argument("--skip-tests", action="store_true")
    parser.add_argument("--skip-pipeline", action="store_true")
    return parser.parse_args()


def _resolve_max_solve_elements(level: str, requested: int | None) -> int:
    if requested is None:
        if level == "full":
            raise ValueError(
                "--level full exige --max-solve-elements explicito para autorizar a carga pesada."
            )
        return 9_852
    if requested < min(profile.element_count for profile in LAB_PROFILES.values()):
        raise ValueError("--max-solve-elements deve autorizar ao menos o perfil de 905 barras.")
    return requested


def main() -> int:
    args = parse_args()
    try:
        max_elements = _resolve_max_solve_elements(args.level, args.max_solve_elements)
    except ValueError as exc:
        raise SystemExit(str(exc)) from exc

    lab_started = perf_counter()
    node = _resolve_node(args.node)
    npm = _resolve_npm(node)
    generated_at = datetime.now(timezone.utc).isoformat(timespec="seconds")
    report_id = datetime.now(timezone.utc).strftime("%Y%m%d-%H%M%S")
    output_dir = args.output_dir.resolve()
    run_dir = output_dir / f"run-{report_id}"
    run_dir.mkdir(parents=True, exist_ok=True)

    test_stages = (
        []
        if args.skip_tests
        else _run_test_stages(
            node,
            npm,
            stress_iterations=10 if args.level == "full" else 3,
        )
    )
    command_results: list[dict[str, object]] = list(test_stages)
    failures = [stage["label"] for stage in test_stages if not stage["ok"]]

    selected_profiles = [
        profile_name
        for profile_name in PROFILE_ORDER
        if LAB_PROFILES[profile_name].element_count <= max_elements
    ]
    direct_entries: list[dict[str, object]] = []
    pipeline_entries: list[dict[str, object]] = []
    frontend_entries: list[dict[str, object]] = []

    for profile_name in selected_profiles:
        profile = LAB_PROFILES[profile_name]
        repetitions = 2 if args.level == "full" and profile.element_count <= 9_852 else 1
        runs, commands = _benchmark_solver_profile(
            profile_name,
            mode="solve",
            repetitions=repetitions,
            max_elements=max_elements,
            run_dir=run_dir,
        )
        command_results.extend(commands)
        failures.extend(result["label"] for result in commands if not result["ok"])
        if runs:
            direct_entries.append({
                "profile": profile_name,
                "nodes": profile.node_count,
                "elements": profile.element_count,
                "scale": runs[0]["scale"],
                "run_count": len(runs),
                "solve_seconds_median": _median(runs, "solve_seconds"),
                "solve_seconds_max": _maximum(runs, "solve_seconds"),
                "total_seconds_median": _median(runs, "total_seconds"),
                "peak_working_set_max_bytes": _maximum(
                    runs, "peak_working_set_after_solve_bytes"
                ),
                "request_json_bytes_median": _median(runs, "request_json_bytes"),
                "response_json_bytes_median": _median(runs, "response_json_bytes"),
                "result_detail": runs[0]["result_detail"],
                "integrity_ok": all(
                    bool(run.get("integrity", {}).get("ok"))
                    for run in runs
                ),
                "runs": runs,
            })

        if not args.skip_pipeline:
            pipeline_runs, pipeline_commands = _benchmark_solver_profile(
                profile_name,
                mode="pipeline",
                repetitions=1,
                max_elements=max_elements,
                run_dir=run_dir,
            )
            command_results.extend(pipeline_commands)
            failures.extend(
                result["label"] for result in pipeline_commands if not result["ok"]
            )
            if pipeline_runs:
                pipeline_entries.append({
                    "profile": profile_name,
                    "nodes": profile.node_count,
                    "elements": profile.element_count,
                    "pipeline_worker_seconds_median": _median(
                        pipeline_runs, "pipeline_worker_seconds"
                    ),
                    "solver_reported_seconds_median": _median(
                        pipeline_runs, "solver_reported_seconds"
                    ),
                    "request_artifact_bytes_median": _median(
                        pipeline_runs, "request_artifact_bytes"
                    ),
                    "response_artifact_bytes_median": _median(
                        pipeline_runs, "response_artifact_bytes"
                    ),
                    "hashes_ok": all(
                        bool(run.get("request_sha256_valid"))
                        and bool(run.get("response_sha256_valid"))
                        and bool(run.get("manifest_sizes_valid"))
                        and bool(run.get("manifest_summary_valid"))
                        for run in pipeline_runs
                    ),
                    "integrity_ok": all(
                        bool(run.get("integrity", {}).get("ok"))
                        for run in pipeline_runs
                    ),
                    "runs": pipeline_runs,
                })

        frontend_metrics, frontend_command = _benchmark_frontend(
            node,
            profile.element_count,
            run_dir,
        )
        command_results.append(frontend_command)
        if not frontend_command["ok"]:
            failures.append(frontend_command["label"])
        if frontend_metrics:
            frontend_entries.append(frontend_metrics)

    for entry in pipeline_entries:
        if not entry["hashes_ok"] or not entry["integrity_ok"]:
            failures.append(f"Integridade de artefatos {entry['profile']}")
    for entry in direct_entries:
        if not entry["integrity_ok"]:
            failures.append(f"Integridade do solver direto {entry['profile']}")
    expected_profiles = set(selected_profiles)
    missing_direct = expected_profiles - {entry["profile"] for entry in direct_entries}
    frontend_element_counts = {int(entry["elements"]) for entry in frontend_entries}
    missing_frontend = {
        profile_name
        for profile_name in selected_profiles
        if LAB_PROFILES[profile_name].element_count not in frontend_element_counts
    }
    missing_pipeline = (
        set()
        if args.skip_pipeline
        else expected_profiles - {entry["profile"] for entry in pipeline_entries}
    )
    failures.extend(f"Solver direto ausente {profile}" for profile in sorted(missing_direct))
    failures.extend(f"Frontend ausente {profile}" for profile in sorted(missing_frontend))
    failures.extend(f"Pipeline ausente {profile}" for profile in sorted(missing_pipeline))
    failures = list(dict.fromkeys(str(failure) for failure in failures))
    report: dict[str, object] = {
        "schema_version": 1,
        "generated_at": generated_at,
        "level": args.level,
        "max_solve_elements": max_elements,
        "duration_seconds": round(perf_counter() - lab_started, 6),
        "ok": not failures,
        "hardware": _hardware_info(node),
        "tests": test_stages,
        "solver_direct": direct_entries,
        "solver_pipeline": pipeline_entries,
        "frontend": frontend_entries,
        "commands": command_results,
        "failures": failures,
    }

    json_payload = json.dumps(report, ensure_ascii=True, indent=2) + "\n"
    markdown_payload = _render_markdown(report)
    json_path = output_dir / f"reliability-{report_id}.json"
    markdown_path = output_dir / f"reliability-{report_id}.md"
    _write_atomic(json_path, json_payload)
    _write_atomic(markdown_path, markdown_payload)
    _write_atomic(output_dir / "latest.json", json_payload)
    _write_atomic(output_dir / "latest.md", markdown_payload)

    print(f"JSON: {json_path}", flush=True)
    print(f"Markdown: {markdown_path}", flush=True)
    print(f"Resultado: {'APROVADO' if report['ok'] else 'FALHOU'}", flush=True)
    return 0 if report["ok"] else 1


if __name__ == "__main__":
    raise SystemExit(main())
