"""Tests for partner/contract CLI commands."""

from __future__ import annotations

import json
from pathlib import Path

from centris_sdk.cli.main import cli


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


def test_partner_init_creates_contract(cli_runner, temp_dir):
    out_dir = temp_dir / "connectors" / "acme"

    result = cli_runner.invoke(
        cli,
        [
            "partner",
            "init",
            "acme",
            "--publisher",
            "acme-inc",
            "--out-dir",
            str(out_dir),
            "--url-pattern",
            "https://app.acme.com/*",
        ],
    )

    assert result.exit_code == 0
    contract_path = out_dir / "centris-contract.json"
    assert contract_path.exists()
    payload = _read_json(contract_path)
    assert payload["ccc"] == "1.0"
    assert payload["app"] == "acme"
    assert payload["publisher"] == "acme-inc"
    assert "core.navigate" in payload["actions"]


def test_contract_validate_json_output(cli_runner, temp_dir):
    out_dir = temp_dir / "connectors" / "example"
    init_result = cli_runner.invoke(
        cli,
        [
            "partner",
            "init",
            "example",
            "--out-dir",
            str(out_dir),
            "--url-pattern",
            "https://example.com/*",
        ],
    )
    assert init_result.exit_code == 0

    contract_path = out_dir / "centris-contract.json"
    validate = cli_runner.invoke(
        cli,
        [
            "contract",
            "validate",
            str(contract_path),
            "--allow-unsigned",
            "--json-output",
        ],
    )

    assert validate.exit_code == 0
    assert '"operation": "contract.validate"' in validate.output
    assert '"ok": true' in validate.output


def test_contract_publish_dry_run(cli_runner, temp_dir):
    out_dir = temp_dir / "connectors" / "publishable"
    init_result = cli_runner.invoke(
        cli,
        [
            "partner",
            "init",
            "publishable",
            "--out-dir",
            str(out_dir),
            "--url-pattern",
            "https://publishable.com/*",
        ],
    )
    assert init_result.exit_code == 0

    contract_path = out_dir / "centris-contract.json"
    publish = cli_runner.invoke(
        cli,
        [
            "contract",
            "publish",
            str(contract_path),
            "--dry-run",
            "--json-output",
        ],
    )
    assert publish.exit_code == 0
    assert '"operation": "contract.publish"' in publish.output
    assert '"dry_run": true' in publish.output
