"""Per-kind probes — presence, JWT decode, skip semantics (SPEC §4 probe verb)."""

from __future__ import annotations

import base64
import json
import time

from mgf.secrets.context import Context
from mgf.secrets.forge import DeployKey
from mgf.secrets.hosts import HostStat
from mgf.secrets.probes import run_probe
from mgf.secrets.registry import load
from tests._fakes import FakeForge, FakeHost


def _entry(tmp_path, text, entry_id):
    p = tmp_path / "SECRETS.toml"
    p.write_text(text, encoding="utf-8")
    return load([p]).get(entry_id)


LOCAL = """\
[t]
family = "mgf"
kind = "password"
purpose = "p"
consumers = ["c"]
recovery = "r"
state = "active"
policy = { allowed_repos = "*", blast_radius = "b" }
rotation = { class = "password", staged = true }
verify = { probe = "login" }
surfaces = [ { type = "local-file", repo = "mgf", path = "tokens/t.txt", mode = "0600" } ]
"""


def test_probe_local_present_ok(tmp_path) -> None:
    e = _entry(tmp_path, LOCAL, "t")
    f = tmp_path / "mgf" / "my_stuff" / "tokens" / "t.txt"
    f.parent.mkdir(parents=True)
    f.write_text("v", encoding="utf-8")
    r = run_probe(e, Context(fed_root=tmp_path))
    assert r.status == "ok" and r.exit_code() == 0


def test_probe_local_missing_is_finding(tmp_path) -> None:
    e = _entry(tmp_path, LOCAL, "t")
    r = run_probe(e, Context(fed_root=tmp_path))
    assert r.status == "finding" and r.exit_code() == 1


JWT = LOCAL.replace('kind = "password"', 'kind = "jwt-minted"')


def _jwt(days):
    def b64(o):
        return base64.urlsafe_b64encode(json.dumps(o).encode()).rstrip(b"=").decode()

    return f"{b64({'alg': 'HS256'})}.{b64({'exp': int(time.time()) + days * 86400})}.s"


def test_probe_jwt_valid_and_expired(tmp_path) -> None:
    e = _entry(tmp_path, JWT, "t")
    f = tmp_path / "mgf" / "my_stuff" / "tokens" / "t.txt"
    f.parent.mkdir(parents=True)
    f.write_text(_jwt(30), encoding="utf-8")
    assert run_probe(e, Context(fed_root=tmp_path)).status == "ok"
    f.write_text(_jwt(-1), encoding="utf-8")
    r = run_probe(e, Context(fed_root=tmp_path))
    assert r.status == "finding" and "EXPIRED" in r.message


DEPLOY = """\
[k]
family = "mgf"
kind = "ssh-deploy-key"
purpose = "p"
consumers = ["c"]
recovery = "r"
state = "active"
policy = { allowed_repos = "*", blast_radius = "b" }
rotation = { class = "static-key", staged = true }
verify = { probe = "fp" }
surfaces = [ { type = "forge-deploy-key", repos = "ALL_MANAGED", readonly = true, title = "ci-clone" } ]
"""


def test_probe_deploy_key_skips_without_forge_client(tmp_path) -> None:
    e = _entry(tmp_path, DEPLOY, "k")
    assert run_probe(e, Context(fed_root=tmp_path)).status == "skipped"


def test_probe_deploy_key_ok_with_forge(tmp_path) -> None:
    e = _entry(tmp_path, DEPLOY, "k")
    ctx = Context(fed_root=tmp_path, forge=FakeForge({"x": [DeployKey("ci-clone", "fp", True)]}))
    assert run_probe(e, ctx).status == "ok"


HOSTSA = """\
[sa]
family = "mgf"
kind = "service-account"
purpose = "p"
consumers = ["c"]
recovery = "r"
state = "active"
policy = { allowed_repos = "*", blast_radius = "b" }
rotation = { class = "sa", staged = true }
verify = { probe = "oo" }
surfaces = [ { type = "host-file", host = "h1", path = "/etc/mgf/x", mode = "0600", owner = "root" } ]
"""


def test_probe_service_account_host(tmp_path) -> None:
    e = _entry(tmp_path, HOSTSA, "sa")
    assert run_probe(e, Context(fed_root=tmp_path)).status == "skipped"
    ctx = Context(
        fed_root=tmp_path,
        hosts=FakeHost({("h1", "/etc/mgf/x"): HostStat("present", mode="600", owner="root")}),
    )
    assert run_probe(e, ctx).status == "ok"
    ctx = Context(fed_root=tmp_path, hosts=FakeHost({("h1", "/etc/mgf/x"): HostStat("missing")}))
    assert run_probe(e, ctx).status == "finding"
    # unreachable (present-but-unverifiable) is skipped, never a finding
    ctx = Context(
        fed_root=tmp_path, hosts=FakeHost({("h1", "/etc/mgf/x"): HostStat("unreachable")})
    )
    assert run_probe(e, ctx).status == "skipped"
