"""E2E: link add/remove file operations.

No K8s cluster needed — tests project file (.kuberoku) operations
via the CLI runner in isolated filesystems.

Run with: pytest tests/e2e/test_link_lifecycle.py -v -s
"""

from __future__ import annotations

import pathlib

import yaml
from click.testing import CliRunner

from kuberoku.branding import PROJECT_FILE_NAME
from kuberoku.cli.main import cli
from kuberoku.config.project import resolve_project_link, write_project_file


def test_00_link_add_simple() -> None:
    """apps:link:add writes .kuberoku, verify file contents."""
    runner = CliRunner()
    with runner.isolated_filesystem() as td:
        result = runner.invoke(cli, ["apps", "link", "add", "myapi"])
        assert result.exit_code == 0
        data = yaml.safe_load(pathlib.Path(td, PROJECT_FILE_NAME).read_text())
        assert data["app"] == "myapi"
        print(f"\n  Linked to myapi, file: {data}")


def test_01_link_add_with_alias() -> None:
    """Multi-env format with --as."""
    runner = CliRunner()
    with runner.isolated_filesystem() as td:
        runner.invoke(cli, ["apps", "link", "add", "myapi-dev", "--as", "dev"])
        runner.invoke(
            cli,
            [
                "apps",
                "link",
                "add",
                "myapi-prod",
                "--as",
                "prod",
                "--cluster",
                "production",
            ],
        )
        data = yaml.safe_load(pathlib.Path(td, PROJECT_FILE_NAME).read_text())
        assert data["default"] == "dev"
        assert data["environments"]["dev"]["app"] == "myapi-dev"
        assert data["environments"]["prod"]["app"] == "myapi-prod"
        assert data["environments"]["prod"]["cluster"] == "production"
        print(f"\n  Multi-env: {data}")


def test_02_link_remove_alias() -> None:
    """Remove one alias, file persists with the other."""
    runner = CliRunner()
    with runner.isolated_filesystem() as td:
        runner.invoke(cli, ["apps", "link", "add", "myapi-dev", "--as", "dev"])
        runner.invoke(cli, ["apps", "link", "add", "myapi-prod", "--as", "prod"])

        result = runner.invoke(cli, ["apps", "link", "remove", "--as", "dev"])
        assert result.exit_code == 0

        data = yaml.safe_load(pathlib.Path(td, PROJECT_FILE_NAME).read_text())
        assert "dev" not in data["environments"]
        assert "prod" in data["environments"]
        print(f"\n  Removed dev, remaining: {data}")


def test_03_link_remove_all() -> None:
    """Remove entire file."""
    runner = CliRunner()
    with runner.isolated_filesystem() as td:
        runner.invoke(cli, ["apps", "link", "add", "myapi"])
        assert pathlib.Path(td, PROJECT_FILE_NAME).exists()

        result = runner.invoke(cli, ["apps", "link", "remove"])
        assert result.exit_code == 0
        assert "Unlinked" in result.output
        assert not pathlib.Path(td, PROJECT_FILE_NAME).exists()
        print("\n  Removed all links")


def test_04_link_resolve_walks_up() -> None:
    """Subdirectory resolves parent's .kuberoku file."""
    runner = CliRunner()
    with runner.isolated_filesystem() as td:
        td_path = pathlib.Path(td)
        write_project_file("myapi", directory=td_path)

        subdir = td_path / "src" / "deep" / "nested"
        subdir.mkdir(parents=True)

        link = resolve_project_link(start_dir=subdir)
        assert link is not None
        assert link.app == "myapi"
        print(f"\n  Resolved from {subdir} -> {link.app}")


def test_05_colon_syntax() -> None:
    """apps:link:add via CLI colon syntax."""
    runner = CliRunner()
    with runner.isolated_filesystem() as td:
        result = runner.invoke(cli, ["apps:link:add", "myapi"])
        assert result.exit_code == 0
        assert "Linked to myapi" in result.output

        result = runner.invoke(cli, ["apps:link:remove"])
        assert result.exit_code == 0
        assert "Unlinked" in result.output
        assert not pathlib.Path(td, PROJECT_FILE_NAME).exists()
        print("\n  Colon syntax verified")
