"""Confluence DOC_REVIEW (already implemented) tests."""

from __future__ import annotations

import pytest

from packages.agents.requirement_analyst import RequirementAnalyst
from packages.db.models import WorkflowState
from packages.integrations.doc_validation import doc_review_comment_body
from packages.integrations.jira_webhook import (
    doc_review_decision,
    normalize_jira_webhook,
    should_resume_doc_review,
)
from packages.knowledge.retrievers import KnowledgeHit, KnowledgeService, MockConfluenceRetriever
from packages.orchestrator.graph import Orchestrator, create_run
from tests.conftest import load_story


def test_doc_review_comment_includes_refs():
    from packages.integrations.doc_validation import DocReference

    body = doc_review_comment_body(
        [DocReference(title="Customer Tier", url="https://example/wiki/1")],
        "Already shipped",
    )
    assert "Customer Tier" in body
    assert "https://example/wiki/1" in body
    assert "continue" in body
    assert "already done" in body


def test_doc_review_decision_keywords():
    cont = normalize_jira_webhook(
        {
            "webhookEvent": "comment_created",
            "issue": {"key": "AN-1", "fields": {}},
            "comment": {"body": "please continue"},
        },
        "d1",
    )
    assert doc_review_decision(cont) == "continue"
    done = normalize_jira_webhook(
        {
            "webhookEvent": "comment_created",
            "issue": {"key": "AN-1", "fields": {}},
            "comment": {"body": "already done"},
        },
        "d2",
    )
    assert doc_review_decision(done) == "close"
    close = normalize_jira_webhook(
        {
            "webhookEvent": "comment_created",
            "issue": {"key": "AN-1", "fields": {}},
            "comment": {"body": "close"},
        },
        "d3",
    )
    assert doc_review_decision(close) == "close"


def test_should_resume_doc_review():
    event = normalize_jira_webhook(
        {
            "webhookEvent": "comment_created",
            "issue": {"key": "AN-1", "fields": {}},
            "comment": {"author": {"accountId": "human-1"}, "body": "continue"},
        },
        "d4",
    )
    assert should_resume_doc_review(event, WorkflowState.DOC_REVIEW) is True
    assert should_resume_doc_review(event, WorkflowState.DUPLICATE_REVIEW) is False


@pytest.mark.asyncio
async def test_doc_review_pause_then_continue(db_session, mock_jira, artifacts_tmpdir):
    issue = load_story("SALES-101")
    mock_jira.seed(issue)

    conf = MockConfluenceRetriever()
    conf.seed(
        KnowledgeHit(
            source="confluence",
            title="Customer_Tier__c already implemented on Account",
            snippet=(
                "Customer_Tier__c picklist on Account (Bronze, Silver, Gold) is already "
                "implemented and deployed. Validation for Gold vs AnnualRevenue is live."
            ),
            url="https://example.atlassian.net/wiki/spaces/ENG/pages/999",
        )
    )
    analyst = RequirementAnalyst(knowledge=KnowledgeService(confluence=conf))
    orch = Orchestrator(db_session, jira=mock_jira, analyst=analyst)

    run = await create_run(db_session, issue.key)
    paused = await orch.run(run.id)
    assert paused.state == WorkflowState.DOC_REVIEW
    assert paused.artifacts.get("doc_already_implemented") is True
    assert any("already exist in Confluence" in c["body"] for c in mock_jira.comments_posted)
    assert any("Customer_Tier__c" in c["body"] for c in mock_jira.comments_posted)

    arts = dict(paused.artifacts or {})
    arts["doc_decision"] = "continue"
    paused.artifacts = arts
    await db_session.flush()

    resumed = await orch.run(run.id, resume=True)
    assert resumed.state == WorkflowState.DESIGN_REVIEW
    assert resumed.artifacts.get("doc_check_skipped") is True


@pytest.mark.asyncio
async def test_doc_review_pause_then_close(db_session, mock_jira, artifacts_tmpdir):
    issue = load_story("SALES-101")
    mock_jira.seed(issue)

    conf = MockConfluenceRetriever()
    conf.seed(
        KnowledgeHit(
            source="confluence",
            title="Customer_Tier__c already implemented on Account",
            snippet="Customer_Tier__c is already implemented on Account and deployed to production.",
            url="https://example.atlassian.net/wiki/spaces/ENG/pages/999",
        )
    )
    analyst = RequirementAnalyst(knowledge=KnowledgeService(confluence=conf))
    orch = Orchestrator(db_session, jira=mock_jira, analyst=analyst)

    run = await create_run(db_session, issue.key)
    paused = await orch.run(run.id)
    assert paused.state == WorkflowState.DOC_REVIEW

    arts = dict(paused.artifacts or {})
    arts["doc_decision"] = "close"
    paused.artifacts = arts
    await db_session.flush()

    closed = await orch.run(run.id, resume=True)
    assert closed.state == WorkflowState.FAILED
    assert "confluence" in (closed.error or "").lower() or "documented" in (closed.error or "").lower()
    assert any("already documented" in c["body"].lower() for c in mock_jira.comments_posted)
