"""Integration tests for the add_comment.py CLI using Typer's CliRunner."""
from pathlib import Path
from unittest.mock import MagicMock

import pytest
from typer.testing import CliRunner

from jps_jira_utils.add_comment import app


def test_cli_requires_jira_id(runner: CliRunner) -> None:
    """Test that the CLI exits with error when no JIRA_ID is provided.

    Args:
        runner: Typer CLI test runner fixture.
    """
    result = runner.invoke(app)
    assert result.exit_code == 2
    # Typer's error message for missing argument is generic and may not mention the argument name
    assert "Usage:" in result.stdout or "Usage:" in result.stderr


@pytest.mark.skip(reason="Not working in GitHub Actions CI")
def test_cli_help_displays_correctly(runner: CliRunner) -> None:
    """Test that --help shows the correct help text.

    Args:
        runner: Typer CLI test runner fixture.
    """
    result = runner.invoke(app, ["--help"], color=False)
    assert result.exit_code == 0
    # Match the actual help string from Typer
    assert "Add a comment and optional attachment to a Jira issue." in result.stdout
    assert "--comment-file" in result.stdout
    assert "--attach-file" in result.stdout


@pytest.mark.skip(reason="Skipping this test")
def test_full_flow_with_comment_file_and_attachment(
    runner: CliRunner,
    tmp_path: Path,
    mock_requests_session: MagicMock,
    monkeypatch,
) -> None:
    """Test complete flow with comment file and attachment (non-interactive).

    Args:
        runner: Typer CLI test runner.
        tmp_path: Temporary directory fixture.
        mock_requests_session: Mocked HTTP POST response.
        monkeypatch: For patching input/confirm.
    """
    # Setup test files
    comment_file = tmp_path / "comment.txt"
    comment_file.write_text("Test comment from file\nLine 2")

    attach_file = tmp_path / "result.log"
    attach_file.write_bytes(b"fake log output\n")

    # Skip all interactive prompts
    monkeypatch.setattr("typer.confirm", lambda *args, **kwargs: True)
    monkeypatch.setattr("builtins.input", lambda *args: "y")
    monkeypatch.setattr("typer.prompt", lambda *args, **kwargs: "Test note")

    # Patch requests.Session to return a mock session with a mock post method
    from unittest.mock import MagicMock

    mock_session = MagicMock()
    mock_comment_response = MagicMock()
    mock_comment_response.ok = True
    mock_comment_response.status_code = 201
    mock_comment_response.json.return_value = {"id": "10055"}
    mock_comment_response.text = ""
    mock_attach_response = MagicMock()
    mock_attach_response.ok = True
    mock_attach_response.status_code = 200
    mock_attach_response.json.return_value = {"id": "attachment-id"}
    mock_attach_response.text = ""
    # Return comment response first, then attachment response
    mock_session.post.side_effect = [mock_comment_response, mock_attach_response]
    monkeypatch.setattr("requests.Session", lambda: mock_session)

    # Set required environment variables for the CLI to succeed
    _ = {
        "JIRA_BASE_URL": "https://example.atlassian.net",
        "JIRA_EMAIL": "user@example.com",
        "JIRA_API_TOKEN": "dummy-token",
    }

    result = runner.invoke(
        app,
        [
            "JPS-9999",
            "--comment-file",
            str(comment_file),
            "--attach-file",
            str(attach_file),
        ],
    )

    assert result.exit_code == 0
    assert "Success! Comment added to JPS-9999" in result.stdout
    assert "Jira URL: https://example.atlassian.net/browse/JPS-9999" in result.stdout
    assert "Wrote the log file to" in result.stdout


def test_interactive_comment_cancellation(
    runner: CliRunner,
    mock_requests_session: MagicMock,
    monkeypatch,
) -> None:
    """Test that user can cancel after entering comment interactively.

    Args:
        runner: Typer CLI test runner.
        mock_requests_session: Mocked HTTP response.
        monkeypatch: To simulate user input.
    """
    user_inputs = iter(
        [
            "This is my comment",
            "",  # blank line
            "",  # second blank line → ends input
            "n",  # cancel at confirmation
        ]
    )

    monkeypatch.setattr("builtins.input", lambda *a: next(user_inputs))
    monkeypatch.setattr("typer.confirm", lambda *a, **k: False)

    result = runner.invoke(app, ["JPS-8888"])

    assert result.exit_code == 0
    assert "Cancelled." in result.stdout
    assert mock_requests_session.json.call_count == 0  # No POST made
