"""Train our artifact, run our own127.0.0.1 child, send real HTTP, terminate only that child."""
import hashlib
import json
import math
import socket
import subprocess
import sys
import time

import httpx
import joblib
import numpy as np

from train_model import ARTIFACTS, BASE, FEATURE_ORDER, MODEL_VERSION

HOST, PORT = "127.0.0.1", 8769


def main():
    train_run = subprocess.run([sys.executable, str(BASE / "train_model.py")],
                               capture_output=True, check=True)
    metadata = json.loads(train_run.stdout)
    fixture = json.loads((ARTIFACTS / "client_fixture.json").read_text())
    own_pipeline = joblib.load(ARTIFACTS / "pipeline.joblib")
    artifact_before = hashlib.sha256((ARTIFACTS / "pipeline.joblib").read_bytes()).hexdigest()
    # Refuse a busy port. Never discover/kill another process or reuse its server.
    with socket.socket() as sock:
        sock.bind((HOST, PORT))
    records = []
    proc = None
    shutdown = None
    log_path = BASE / "server-run.log"
    with log_path.open("w") as log, httpx.Client(base_url=f"http://{HOST}:{PORT}",
            timeout=5, trust_env=False) as client:
        try:
            proc = subprocess.Popen([sys.executable, "-m", "uvicorn", "api_app:app",
                "--host", HOST, "--port", str(PORT), "--log-level", "warning"],
                cwd=BASE, stdout=log, stderr=log)
            for _ in range(100):
                if proc.poll() is not None:
                    raise RuntimeError("Our server exited before readiness; inspect local server-run.log")
                try:
                    response = client.get("/health")
                    if response.status_code == 200:
                        ready = response.json()
                        assert ready["model_version"] == MODEL_VERSION
                        assert ready["artifact_sha256"] == artifact_before
                        break
                except httpx.TransportError:
                    pass
                time.sleep(.05)
            else:
                raise RuntimeError("Our server did not become ready")
            records.append({"case": "health_after_startup", "status": response.status_code, "body": ready})
            valid = [("single", {"rows": fixture["rows"][:1]}),
                ("batch3", {"rows": fixture["rows"]}),
                ("integer_numbers", {"rows": [[0, 1, -2, 3]]}),
                ("maximum_batch32", {"rows": [fixture["rows"][0]] * 32})]
            probability_errors = []
            for name, payload in valid:
                response = client.post("/predict", json=payload)
                assert response.status_code == 200, response.text
                body = response.json()
                x = np.asarray(payload["rows"], dtype=float)
                expected_class = own_pipeline.predict(x).tolist()
                expected_prob = own_pipeline.predict_proba(x)[:, 1]
                scale = own_pipeline.named_steps["scale"]
                classifier = own_pipeline.named_steps["classifier"]
                # Independent explicit transform + dot + sigmoid; do not use Pipeline.transform.
                z = (x - scale.mean_) / scale.scale_
                logits = z @ classifier.coef_[0] + classifier.intercept_[0]
                manual_prob = np.array([1 / (1 + math.exp(-float(v))) for v in logits])
                got = body["predictions"]
                assert [v["class"] for v in got] == expected_class
                error = max(abs(np.array([v["probability_class_1"] for v in got]) - manual_prob))
                probability_errors.append(float(error))
                assert np.allclose(expected_prob, manual_prob, atol=1e-14, rtol=0)
                assert error < 1e-14 and body["model_version"] == MODEL_VERSION
                records.append({"case": name, "status": response.status_code,
                    "request": payload, "body": body})
            invalid = [("empty_batch", {"rows": []}),
                ("too_many_rows", {"rows": [[0, 0, 0, 0]] * 33}),
                ("row3", {"rows": [[0, 0, 0]]}), ("row5", {"rows": [[0, 0, 0, 0, 0]]}),
                ("numeric_string", {"rows": [["1.0", 0, 0, 0]]}),
                ("bool", {"rows": [[True, 0, 0, 0]]}), ("null", {"rows": [[None, 0, 0, 0]]}),
                ("extra_field", {"rows": [[0, 0, 0, 0]], "debug": True}),
                ("missing_rows", {}), ("rows_not_matrix", {"rows": [0, 1, 2, 3]}),
                ("finite_but_overflowing_magnitude", {"rows": [[1e308, 1e308, 1e308, 1e308]]})]
            for name, payload in invalid:
                response = client.post("/predict", json=payload)
                assert response.status_code == 422, (name, response.text)
                assert response.headers["content-type"].startswith("application/json")
                records.append({"case": name, "status": response.status_code,
                    "request": payload, "body": response.json()})
            raw_cases = [("raw_NaN", '{"rows":[[NaN,0,0,0]]}'),
                ("raw_Infinity", '{"rows":[[Infinity,0,0,0]]}'),
                ("raw_negative_Infinity", '{"rows":[[-Infinity,0,0,0]]}'),
                ("exponent_overflow_1e400", '{"rows":[[1e400,0,0,0]]}'),
                ("malformed_json", '{"rows":')]
            for name, raw in raw_cases:
                response = client.post("/predict", content=raw, headers={"Content-Type": "application/json"})
                assert response.status_code == 422, (name, response.text)
                body = response.json()
                assert all(set(error) == {"type", "loc", "msg"} for error in body["detail"])
                records.append({"case": name, "status": response.status_code, "raw_request": raw, "body": body})
            response = client.get("/health")
            assert response.status_code == 200 and response.json()["model_load_count"] == 1
            records.append({"case": "health_after_all_requests", "status": 200, "body": response.json()})
        finally:
            if proc is not None:
                if proc.poll() is None:
                    proc.terminate()
                    try:
                        proc.wait(timeout=5)
                    except subprocess.TimeoutExpired:
                        proc.kill()
                        proc.wait(timeout=5)
                shutdown = {"owned_child_reaped": proc.poll() is not None,
                            "exit_code": proc.returncode, "host": HOST, "port": PORT}
    artifact_after = hashlib.sha256((ARTIFACTS / "pipeline.joblib").read_bytes()).hexdigest()
    assert artifact_before == artifact_after
    print(json.dumps({"scope": "Original localhost-only trained toy Pipeline API, actual HTTP, no public deployment",
        "metadata": metadata, "request_results": records,
        "checks": {"manual_pipeline_probability_max_error": max(probability_errors),
            "artifact_unchanged_by_requests": artifact_before == artifact_after,
            "model_load_count_after_requests": 1, "feature_order": FEATURE_ORDER,
            "probability_semantics": "class1 probability; not assurance the predicted class is calibrated",
            "validation_errors_do_not_echo_input_or_ctx": True},
        "server_shutdown": shutdown,
        "limits": ["Synthetic fixed split only, no CV/hyperparameter tuning or real-world model quality.",
            "All four values are positional according to metadata; numeric column swaps cannot be semantically detected.",
            "Strict input accepts JSON ints/floats, rejects strings/bools/null/nonfinite; finite numeric overflow gets422.",
            "NaN/Infinity tokens are nonstandard JSON; current parser accepts them before finite validation rejects them.",
            "Custom validation errors expose type/loc/msg only, preventing nonfinite input echo serialization failures.",
            "joblib loading only own trusted local artifact; matching digest alone does not make hostile pickle safe.",
            "Model/environment metadata is checked at startup; no arbitrary upload/load endpoint or request fit.",
            "No auth, public serving, TLS, concurrency/load test, monitoring, calibration or production deployment claim.",
            "Only the Popen child created here is terminated/reaped; no process discovery or unrelated termination."]}, indent=2, allow_nan=False))


if __name__ == "__main__":
    main()
