"""Tests for the product sub-applications wired into the main CLI."""

from __future__ import annotations

import json
import sqlite3
from pathlib import Path

import pytest
from typer.testing import CliRunner

from cyberbrain26.cli import app
from cyberbrain26.product.doctor import _check_workspaces_root, run_checks
from cyberbrain26.product.local_store import (
    ENV_WORKSPACES_ROOT,
    resolve_db_path,
    workspaces_root,
)

runner = CliRunner()

# The stale claim was: "A writable workspace path handed to the sandbox is trusted by
# design". Sandbox workspaces are confined to a sanctioned root, so that phrasing must
# never come back.
STALE_WORKSPACE_CLAIM: str = "is trusted by design"
# The security-relevant part of the corrected wording, pinned as a substring.
WORKSPACE_CONFINEMENT_CLAIM: str = "refused before any process is launched"


def test_top_level_help_lists_product_commands() -> None:
    result = runner.invoke(app, ["--help"])
    assert result.exit_code == 0
    assert "approvals" in result.output
    assert "doctor" in result.output


def test_approvals_help() -> None:
    result = runner.invoke(app, ["approvals", "--help"])
    assert result.exit_code == 0
    for cmd in ("pending", "show", "approve", "deny", "history"):
        assert cmd in result.output


def test_doctor_help() -> None:
    result = runner.invoke(app, ["doctor", "--help"])
    assert result.exit_code == 0
    for cmd in ("check", "main"):
        assert cmd in result.output


def test_doctor_never_prints_secret_values(
    monkeypatch: pytest.MonkeyPatch, tmp_path: Path
) -> None:
    secret_value = "DO-NOT-PRINT-THIS-SECRET-7c3f1e9a"
    monkeypatch.setenv("OPENAI_API_KEY", secret_value)
    result = runner.invoke(app, ["doctor", "check", "--data-dir", str(tmp_path)])
    assert result.exit_code in (0, 1)
    assert secret_value not in result.output
    result_json = runner.invoke(
        app, ["doctor", "check", "--data-dir", str(tmp_path), "--json"]
    )
    assert result_json.exit_code in (0, 1)
    assert secret_value not in result_json.output


def test_approvals_pending_on_empty_db_fails_closed(tmp_path: Path) -> None:
    result = runner.invoke(
        app, ["approvals", "pending", "--no-persist", "--data-dir", str(tmp_path)]
    )
    assert result.exit_code != 0
    assert "Traceback" not in result.output


def test_approvals_approve_unknown_id_fails_closed(tmp_path: Path) -> None:
    result = runner.invoke(
        app,
        [
            "approvals",
            "approve",
            "nonexistent-request-id",
            "--data-dir",
            str(tmp_path),
        ],
    )
    assert result.exit_code != 0
    assert "Traceback" not in result.output
    assert "approved" not in result.output.lower()
    db_path = resolve_db_path(data_dir=tmp_path)
    conn = sqlite3.connect(str(db_path))
    try:
        approved_count = conn.execute(
            "SELECT COUNT(*) FROM audit_events WHERE result = ?",
            ("approved",),
        ).fetchone()[0]
        assert approved_count == 0
        record_count = conn.execute(
            "SELECT COUNT(*) FROM approval_records"
        ).fetchone()[0]
        assert record_count == 0
    finally:
        conn.close()


def _doctor_text(tmp_path: Path, *args: str) -> str:
    """Return the plain-text ``doctor check`` output for an isolated data directory."""
    result = runner.invoke(app, ["doctor", "check", "--data-dir", str(tmp_path), *args])
    assert result.exit_code in (0, 1)
    return result.output


def test_doctor_reports_workspace_confinement_and_not_the_stale_claim(
    tmp_path: Path,
) -> None:
    output = _doctor_text(tmp_path)
    assert STALE_WORKSPACE_CLAIM not in output
    assert WORKSPACE_CONFINEMENT_CLAIM in output
    assert "confinement" in output or "confined" in output


def test_doctor_json_reports_workspace_confinement_and_not_the_stale_claim(
    tmp_path: Path,
) -> None:
    output = _doctor_text(tmp_path, "--json")
    assert STALE_WORKSPACE_CLAIM not in output
    assert WORKSPACE_CONFINEMENT_CLAIM in output


def test_doctor_sandbox_limits_check_does_not_claim_unconfined_workspaces(
    tmp_path: Path,
) -> None:
    output = _doctor_text(tmp_path)
    sandbox_row = next(line for line in output.splitlines() if line.lstrip().startswith("WARN  sandbox_limits"))
    assert STALE_WORKSPACE_CLAIM not in sandbox_row
    assert WORKSPACE_CONFINEMENT_CLAIM in sandbox_row


def test_workspaces_root_check_warns_when_root_is_missing(tmp_path: Path) -> None:
    result = _check_workspaces_root(tmp_path)
    assert result.name == "workspaces_root"
    assert result.status == "warn"
    assert result.metadata["path"] == str(workspaces_root(tmp_path))
    assert result.metadata["exists"] is False
    assert WORKSPACE_CONFINEMENT_CLAIM in result.detail


def test_workspaces_root_check_warns_when_root_is_world_readable(tmp_path: Path) -> None:
    root = workspaces_root(tmp_path)
    root.mkdir(parents=True)
    root.chmod(0o755)
    result = _check_workspaces_root(tmp_path)
    assert result.status == "warn"
    assert result.metadata["mode"] == oct(0o755)
    assert "owner-only" in result.detail
    assert WORKSPACE_CONFINEMENT_CLAIM in result.detail


def test_workspaces_root_check_passes_when_root_is_owner_only(tmp_path: Path) -> None:
    root = workspaces_root(tmp_path)
    root.mkdir(parents=True)
    root.chmod(0o700)
    result = _check_workspaces_root(tmp_path)
    assert result.status == "pass"
    assert result.metadata["mode"] == oct(0o700)
    assert WORKSPACE_CONFINEMENT_CLAIM in result.detail


def test_workspaces_root_check_honours_configured_root(
    monkeypatch: pytest.MonkeyPatch, tmp_path: Path
) -> None:
    configured = tmp_path / "elsewhere"
    configured.mkdir()
    configured.chmod(0o700)
    monkeypatch.setenv(ENV_WORKSPACES_ROOT, str(configured))
    result = _check_workspaces_root(tmp_path)
    assert result.status == "pass"
    assert result.metadata["path"] == str(configured)
    assert result.metadata["source"] == ENV_WORKSPACES_ROOT


def test_workspaces_root_check_never_creates_the_root(tmp_path: Path) -> None:
    result = _check_workspaces_root(tmp_path)
    assert result.status == "warn"
    assert not workspaces_root(tmp_path).exists()
    assert not (tmp_path / "cyberbrain.sqlite3").exists()


def test_workspaces_root_check_is_reported_in_order(tmp_path: Path) -> None:
    names = [check.name for check in run_checks(data_dir=tmp_path)]
    assert "workspaces_root" in names
    assert names.index("sandbox_limits") < names.index("workspaces_root")
    assert "workspaces_root" in _doctor_text(tmp_path)


def test_workspaces_root_row_counts_toward_strict_and_json(
    monkeypatch: pytest.MonkeyPatch, tmp_path: Path
) -> None:
    root = workspaces_root(tmp_path)
    root.mkdir(parents=True)
    root.chmod(0o755)
    monkeypatch.setenv(ENV_WORKSPACES_ROOT, str(root))
    strict_result = runner.invoke(
        app, ["doctor", "check", "--data-dir", str(tmp_path), "--strict"]
    )
    assert strict_result.exit_code == 1
    assert "WARN  workspaces_root" in strict_result.output
    json_result = runner.invoke(
        app, ["doctor", "check", "--data-dir", str(tmp_path), "--json", "--strict"]
    )
    assert json_result.exit_code == 1
    payload = json.loads(json_result.output)
    row = next(item for item in payload["checks"] if item["name"] == "workspaces_root")
    assert row["status"] == "warn"
    assert row["metadata"]["path"] == str(root)
    assert payload["strict"] is True
    assert payload["overall_status"] == "fail"
