"""Git GIT_REVIEW (already implemented in the SFDX repo) tests."""

from __future__ import annotations

from typing import List

import pytest

from packages.agents.requirement_analyst import RequirementAnalyst
from packages.db.models import WorkflowState
from packages.db.artifacts import ArtifactStore
from packages.integrations.code_validation import (
    GIT_EXISTING_CODE_HEADING,
    GIT_REVIEW_HEADING,
    build_git_check_prompt,
    git_search_query,
)
from packages.integrations.github_search import CodeEvidence, GitHubEvidence, MockGitHubSearch
from packages.integrations.jira_webhook import normalize_jira_webhook, should_resume_git_review
from packages.knowledge.retrievers import KnowledgeHit, KnowledgeService, MockConfluenceRetriever
from packages.orchestrator.graph import Orchestrator, create_run
from tests.conftest import load_story

FIELD_PATH = "force-app/main/default/objects/Account/fields/Customer_Tier__c.field-meta.xml"


class FakeRepo:
    def __init__(self, hits: List[KnowledgeHit]) -> None:
        self.hits = hits
        self.queries: List[str] = []

    async def search(self, query: str, limit: int = 5) -> List[KnowledgeHit]:
        self.queries.append(query)
        return self.hits[:limit]


def _implemented_repo() -> FakeRepo:
    return FakeRepo(
        [
            KnowledgeHit(source="git", title="Repository inventory (acme/sfdx)", snippet="Existing metadata: 1 CustomField."),
            KnowledgeHit(
                source="git",
                title=f"{FIELD_PATH} [CustomField]",
                snippet=(
                    "<CustomField><fullName>Customer_Tier__c</fullName><label>Customer Tier</label>"
                    "<type>Picklist</type> Bronze Silver Gold — already implemented on Account</CustomField>"
                ),
                url=f"https://github.com/acme/sfdx/blob/main/{FIELD_PATH}",
            ),
        ]
    )


def _orchestrator(db_session, mock_jira, repo: FakeRepo, code_search=None) -> Orchestrator:
    analyst = RequirementAnalyst(knowledge=KnowledgeService(confluence=MockConfluenceRetriever(), repo=repo))
    return Orchestrator(db_session, jira=mock_jira, analyst=analyst, code_search=code_search)


def _inventory_only() -> FakeRepo:
    return FakeRepo([KnowledgeHit(source="git", title="Repository inventory (acme/sfdx)", snippet="empty")])


def test_git_query_keeps_api_names():
    issue = load_story("SALES-101")
    query = git_search_query(issue)
    assert issue.summary in query
    assert "Customer_Tier__c" in query


def test_git_prompt_lists_exact_matches():
    issue = load_story("SALES-101")
    prompt = build_git_check_prompt(issue, _implemented_repo().hits[1:], "Existing metadata: 1 CustomField.")
    assert "REPOSITORY FILES:" in prompt
    assert "Exact API-name matches in repo: Customer_Tier__c" in prompt


def test_should_resume_git_review_ignores_bot_comment():
    human = normalize_jira_webhook(
        {
            "webhookEvent": "comment_created",
            "issue": {"key": "AN-1", "fields": {}},
            "comment": {"author": {"accountId": "human-1"}, "body": "already done"},
        },
        "g1",
    )
    bot = normalize_jira_webhook(
        {
            "webhookEvent": "comment_created",
            "issue": {"key": "AN-1", "fields": {}},
            "comment": {"body": f"## {GIT_REVIEW_HEADING}\nreply continue or close"},
        },
        "g2",
    )
    assert should_resume_git_review(human, WorkflowState.GIT_REVIEW) is True
    assert should_resume_git_review(human, WorkflowState.DOC_REVIEW) is False
    assert should_resume_git_review(bot, WorkflowState.GIT_REVIEW) is False


@pytest.mark.asyncio
async def test_git_review_pause_then_continue(db_session, mock_jira, artifacts_tmpdir):
    issue = load_story("SALES-101")
    mock_jira.seed(issue)
    repo = _implemented_repo()
    orch = _orchestrator(db_session, mock_jira, repo)

    run = await create_run(db_session, issue.key)
    paused = await orch.run(run.id)
    assert paused.state == WorkflowState.GIT_REVIEW
    assert paused.artifacts["git_references"][0]["url"].endswith(FIELD_PATH)
    assert any(GIT_REVIEW_HEADING in c["body"] for c in mock_jira.comments_posted)
    assert "Customer_Tier__c" in repo.queries[0]

    arts = dict(paused.artifacts or {})
    arts["git_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("git_check_skipped") is True


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

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

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

    closed = await orch.run(run.id, resume=True)
    assert closed.state == WorkflowState.FAILED
    assert "git" in (closed.error or "").lower()


@pytest.mark.asyncio
async def test_doc_review_continue_then_git_review(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 is already implemented and deployed.",
            url="https://example.atlassian.net/wiki/spaces/ENG/pages/999",
        )
    )
    analyst = RequirementAnalyst(knowledge=KnowledgeService(confluence=conf, repo=_implemented_repo()))
    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"] = "continue"
    paused.artifacts = arts
    await db_session.flush()

    git_paused = await orch.run(run.id, resume=True)
    assert git_paused.state == WorkflowState.GIT_REVIEW


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

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


def test_git_prompt_includes_github_evidence_sections():
    issue = load_story("SALES-101")
    ev = GitHubEvidence(
        ticket_refs=[
            CodeEvidence(kind="pr", repo="acme/sfdx", title="SALES-101 tier", url="https://github.com/acme/sfdx/pull/3", ref="3", state="merged")
        ]
    )
    prompt = build_git_check_prompt(issue, [], "", ev)
    assert "CODE MATCHES:\n(none)" in prompt
    assert "- Title: [pr merged] acme/sfdx@3: SALES-101 tier" in prompt
    assert "OPEN PR FILES:" in prompt
    assert "partially_implemented=true" in prompt


@pytest.mark.asyncio
async def test_merged_pr_for_ticket_pauses_in_git_review(db_session, mock_jira, artifacts_tmpdir):
    issue = load_story("SALES-101")
    mock_jira.seed(issue)
    search = MockGitHubSearch(
        GitHubEvidence(
            code=[
                CodeEvidence(
                    kind="code",
                    repo="acme/other-org-repo",
                    title=FIELD_PATH,
                    url=f"https://github.com/acme/other-org-repo/blob/main/{FIELD_PATH}",
                    snippet="<fullName>Customer_Tier__c</fullName> Picklist Bronze Silver Gold on Account",
                    state="default",
                )
            ],
            ticket_refs=[
                CodeEvidence(
                    kind="pr",
                    repo="acme/other-org-repo",
                    title="SALES-101 Customer Tier picklist and validation on Account",
                    url="https://github.com/acme/other-org-repo/pull/12",
                    ref="12",
                    state="merged",
                )
            ],
        )
    )
    orch = _orchestrator(db_session, mock_jira, _inventory_only(), code_search=search)

    run = await create_run(db_session, issue.key)
    paused = await orch.run(run.id)
    assert paused.state == WorkflowState.GIT_REVIEW
    assert search.calls[0]["jira_key"] == "SALES-101"
    assert any(GIT_REVIEW_HEADING in c["body"] for c in mock_jira.comments_posted)
    saved = ArtifactStore().read_json(run.id, "existing-code.json")
    assert any(e["kind"] == "pr" and e["state"] == "merged" for e in saved)


@pytest.mark.asyncio
async def test_partial_match_continues_and_feeds_architect(db_session, mock_jira, artifacts_tmpdir):
    issue = load_story("SALES-101")
    mock_jira.seed(issue)
    search = MockGitHubSearch(
        GitHubEvidence(
            ticket_refs=[
                CodeEvidence(
                    kind="pr",
                    repo="acme/sfdx",
                    title="WIP SALES-101 Customer Tier",
                    url="https://github.com/acme/sfdx/pull/7",
                    ref="7",
                    state="open",
                )
            ],
            pr_files=[
                CodeEvidence(
                    kind="pr_file",
                    repo="acme/sfdx",
                    title="force-app/main/default/classes/TierService.cls",
                    url="https://github.com/acme/sfdx/blob/wip/force-app/main/default/classes/TierService.cls",
                    snippet="+ public class TierService {}",
                    ref="wip/SALES-101",
                    state="open",
                )
            ],
        )
    )
    orch = _orchestrator(db_session, mock_jira, _inventory_only(), code_search=search)

    run = await create_run(db_session, issue.key)
    result = await orch.run(run.id)
    assert result.state == WorkflowState.DESIGN_REVIEW
    assert result.artifacts.get("existing_code")
    assert not any(GIT_REVIEW_HEADING in c["body"] for c in mock_jira.comments_posted)
    note = next(c["body"] for c in mock_jira.comments_posted if GIT_EXISTING_CODE_HEADING in c["body"])
    assert "https://github.com/acme/sfdx/pull/7" in note

    saved = ArtifactStore().read_json(run.id, "existing-code.json")
    assert {e["kind"] for e in saved} >= {"pr"}
    design = ArtifactStore().read_json(run.id, "design.json")
    assert any("Open PR for SALES-101" in r for r in design["risks_or_escalations"])


@pytest.mark.asyncio
async def test_github_search_failure_continues(db_session, mock_jira, artifacts_tmpdir):
    class Broken:
        async def gather(self, *_a, **_k):
            raise RuntimeError("boom")

    issue = load_story("SALES-101")
    mock_jira.seed(issue)
    orch = _orchestrator(db_session, mock_jira, _inventory_only(), code_search=Broken())

    run = await create_run(db_session, issue.key)
    result = await orch.run(run.id)
    assert result.state == WorkflowState.DESIGN_REVIEW
    assert not result.artifacts.get("existing_code")


def test_existing_code_note_does_not_resume_clarification():
    from packages.integrations.jira_webhook import should_resume_clarification

    note = normalize_jira_webhook(
        {
            "webhookEvent": "comment_created",
            "issue": {"key": "AN-1", "fields": {}},
            "comment": {"body": f"## {GIT_EXISTING_CODE_HEADING}\nfiles"},
        },
        "g3",
    )
    assert should_resume_clarification(note, WorkflowState.NEEDS_CLARIFICATION) is False
