"""Tests for M0: project skeleton, database, and health endpoints."""

import sqlite3

from radix_edge.config import get_config, reset_config
from radix_edge.db import init_db, get_db
from radix_edge.models import Job, JobStatus, GPU, GPUStatus, BrainParams


class TestConfig:
    def test_defaults(self, monkeypatch):
        monkeypatch.delenv("RADIX_LOG_LEVEL", raising=False)
        reset_config()
        config = get_config()
        assert config.port == 8080
        assert config.log_level == "INFO"
        assert config.lambda_uncertainty == 0.3
        assert config.beta_exploration == 0.7
        assert config.fep_enabled is True

    def test_scheduler_defaults(self):
        config = get_config()
        assert config.scheduler_policy == "priority"
        assert config.exploration_cap == 0.25
        assert config.enable_sinkhorn is False


class TestDatabase:
    def test_schema_creates_all_tables(self, db):
        tables = [
            row["name"]
            for row in db.execute(
                "SELECT name FROM sqlite_master WHERE type='table' AND name NOT LIKE 'sqlite_%' ORDER BY name"
            ).fetchall()
        ]
        expected = [
            "brain_audit", "brain_params", "config", "fep_decisions", "fep_state",
            "gpu_observations", "gpus", "jobs", "scheduler_interference",
            "scheduler_stats", "usage_accounting", "user_quotas",
        ]
        assert sorted(tables) == sorted(expected)

    def test_brain_params_seeded(self, db):
        row = db.execute("SELECT * FROM brain_params WHERE key = 'current'").fetchone()
        assert row is not None
        assert row["tau"] == 0.8
        assert row["w_queue_depth"] == 0.5

    def test_wal_mode(self, db):
        mode = db.execute("PRAGMA journal_mode").fetchone()[0]
        assert mode == "wal"

    def test_insert_job(self, db):
        db.execute(
            "INSERT INTO jobs (job_id, user_id, image) VALUES (?, ?, ?)",
            ("job-001", "user-a", "nvidia/cuda:12.4"),
        )
        db.commit()
        row = db.execute("SELECT * FROM jobs WHERE job_id = 'job-001'").fetchone()
        assert row["user_id"] == "user-a"
        assert row["status"] == "queued"
        assert row["priority"] == 5
        assert row["num_gpus"] == 1

    def test_insert_gpu(self, db):
        db.execute(
            "INSERT INTO gpus (gpu_index, name, memory_total_mb) VALUES (?, ?, ?)",
            (0, "NVIDIA A100-SXM4-80GB", 81920),
        )
        db.commit()
        row = db.execute("SELECT * FROM gpus WHERE gpu_index = 0").fetchone()
        assert row["name"] == "NVIDIA A100-SXM4-80GB"
        assert row["status"] == "idle"


class TestModels:
    def test_job_from_row(self, db):
        db.execute(
            "INSERT INTO jobs (job_id, user_id, image, command, status) VALUES (?, ?, ?, ?, ?)",
            ("job-002", "user-b", "myimg:latest", '["python", "train.py"]', "running"),
        )
        db.commit()
        row = db.execute("SELECT * FROM jobs WHERE job_id = 'job-002'").fetchone()
        job = Job.from_row(row)
        assert job.job_id == "job-002"
        assert job.status == JobStatus.RUNNING
        assert job.command == ["python", "train.py"]

    def test_job_to_dict(self):
        job = Job(job_id="j1", user_id="u1", image="img:1", status=JobStatus.QUEUED)
        d = job.to_dict()
        assert d["status"] == "queued"
        assert d["job_id"] == "j1"

    def test_gpu_from_row(self, db):
        db.execute(
            "INSERT INTO gpus (gpu_index, name, memory_total_mb, nvlink_peers) VALUES (?, ?, ?, ?)",
            (0, "A100", 81920, "[1, 2]"),
        )
        db.commit()
        row = db.execute("SELECT * FROM gpus WHERE gpu_index = 0").fetchone()
        gpu = GPU.from_row(row)
        assert gpu.nvlink_peers == [1, 2]
        assert gpu.status == GPUStatus.IDLE

    def test_brain_params_from_row(self, db):
        row = db.execute("SELECT * FROM brain_params WHERE key = 'current'").fetchone()
        params = BrainParams.from_row(row)
        assert params.w_queue_depth == 0.5
        assert params.w_gpu_saturation == 0.3
        assert params.w_node_pressure == 0.2


class TestHealthEndpoints:
    def test_healthz(self, client):
        resp = client.get("/healthz")
        assert resp.status_code == 200
        assert resp.json()["status"] == "healthy"

    def test_readyz(self, client):
        resp = client.get("/readyz")
        assert resp.status_code == 200
        assert resp.json()["status"] == "ready"

    def test_metrics(self, client):
        resp = client.get("/metrics")
        assert resp.status_code == 200
        body = resp.text
        assert "radix_job_queue_depth" in body
        assert "radix_brain_weight" in body
