"""GitHub evidence search (code, ticket key, open PR files) tests."""

from __future__ import annotations

from typing import Dict, List

import httpx
import pytest

from packages.config import Settings
from packages.integrations.github_search import (
    TEXT_MATCH_ACCEPT,
    HttpGitHubSearch,
    MockGitHubSearch,
    get_github_search,
    key_pattern,
    search_terms,
)

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


def _settings(**overrides) -> Settings:
    base = dict(
        _env_file=None,
        git_provider="github",
        git_repo_url="https://github.com/acme/sfdx",
        github_token="t0k",
        github_api_base_url="https://api.github.test",
    )
    base.update(overrides)
    return Settings(**base)


class Recorder:
    def __init__(self, routes: Dict[str, object], fail: Dict[str, int] | None = None) -> None:
        self.routes = routes
        self.fail = fail or {}
        self.requests: List[httpx.Request] = []

    def __call__(self, request: httpx.Request) -> httpx.Response:
        self.requests.append(request)
        path = request.url.path
        if path in self.fail:
            return httpx.Response(self.fail[path], json={"message": "API rate limit exceeded"})
        if path not in self.routes:
            return httpx.Response(404, json={"message": "Not Found"})
        return httpx.Response(200, json=self.routes[path])

    def queries(self, path: str) -> List[str]:
        return [r.url.params.get("q", "") for r in self.requests if r.url.path == path]


def _routes() -> Dict[str, object]:
    return {
        "/search/code": {
            "items": [
                {
                    "path": FIELD_PATH,
                    "html_url": f"https://github.com/acme/sfdx/blob/main/{FIELD_PATH}",
                    "repository": {"full_name": "acme/sfdx"},
                    "text_matches": [{"fragment": "<fullName>Customer_Tier__c</fullName>"}],
                }
            ]
        },
        "/search/commits": {
            "items": [
                {
                    "sha": "abc123def4567890",
                    "html_url": "https://github.com/acme/sfdx/commit/abc123def4567890",
                    "commit": {"message": "SALES-101 add Customer Tier field"},
                    "repository": {"full_name": "acme/sfdx"},
                },
                {
                    "sha": "fff",
                    "html_url": "https://github.com/acme/sfdx/commit/fff",
                    "commit": {"message": "SALES-1010 unrelated"},
                    "repository": {"full_name": "acme/sfdx"},
                },
            ]
        },
        "/search/issues": {
            "items": [
                {
                    "number": 7,
                    "title": "[Agent Nova] SALES-101",
                    "body": "Tier field",
                    "state": "open",
                    "html_url": "https://github.com/acme/sfdx/pull/7",
                    "repository_url": "https://api.github.test/repos/acme/sfdx",
                    "pull_request": {"merged_at": None},
                }
            ]
        },
        "/repos/acme/sfdx/pulls/7": {"head": {"ref": "agent-nova/SALES-101"}},
        "/repos/acme/sfdx/branches": [{"name": "agent-nova/SALES-101"}, {"name": "feature/SALES-1010"}],
        "/repos/acme/sfdx/pulls": [
            {"number": 7, "title": "[Agent Nova] SALES-101", "head": {"ref": "agent-nova/SALES-101"}},
            {"number": 9, "title": "Opportunity cleanup", "head": {"ref": "opp"}},
        ],
        "/repos/acme/sfdx/pulls/7/files": [
            {"filename": "force-app/main/default/classes/TierService.cls", "patch": "+ class TierService {}"}
        ],
        "/repos/acme/sfdx/pulls/9/files": [
            {"filename": "force-app/main/default/classes/OppCleanup.cls", "patch": "+ cleanup"},
            {
                "filename": "force-app/main/default/flows/Account_Tier.flow-meta.xml",
                "patch": "+ <field>Customer_Tier__c</field>",
                "blob_url": "https://github.com/acme/sfdx/blob/opp/force-app/main/default/flows/Account_Tier.flow-meta.xml",
            },
        ],
    }


def test_search_terms_and_key_pattern():
    names, keywords = search_terms(
        "Add Customer Tier custom field on Account", "Customer_Tier__c picklist"
    )
    assert names == ["Customer_Tier__c"]
    assert "Customer" in keywords and "Tier" in keywords
    pat = key_pattern("SALES-101")
    assert pat.search("agent-nova/SALES-101")
    assert not pat.search("SALES-1010")


def test_code_queries_org_vs_repo_scope():
    org = HttpGitHubSearch(_settings())
    assert org.qualifier == "org:acme"
    repo = HttpGitHubSearch(_settings(github_search_scope="repo"))
    assert repo.qualifier == "repo:acme/sfdx"
    queries = repo.code_queries(["A__c", "B__c"], ["Customer", "Tier"])
    assert queries[0] == '"A__c" repo:acme/sfdx'
    assert queries[-1] == '"Customer" "Tier" repo:acme/sfdx'
    capped = HttpGitHubSearch(_settings(github_search_max_queries=1)).code_queries(["A__c", "B__c"], ["X"])
    assert len(capped) == 1


@pytest.mark.asyncio
async def test_gather_collects_all_kinds():
    rec = Recorder(_routes())
    search = HttpGitHubSearch(_settings(), transport=httpx.MockTransport(rec))
    ev = await search.gather(
        "SALES-101",
        "Add Customer Tier custom field on Account",
        "Add a Customer_Tier__c picklist on Account",
    )

    assert not ev.errors
    assert [c.title for c in ev.code] == [FIELD_PATH]
    assert "Customer_Tier__c" in ev.code[0].snippet
    code_req = next(r for r in rec.requests if r.url.path == "/search/code")
    assert code_req.headers["Accept"] == TEXT_MATCH_ACCEPT
    assert code_req.headers["Authorization"] == "Bearer t0k"
    assert all("org:acme" in q for q in rec.queries("/search/code"))

    kinds = {(e.kind, e.state) for e in ev.ticket_refs}
    assert ("commit", "default") in kinds
    assert ("pr", "open") in kinds
    assert ("branch", "open") in kinds
    assert not any("SALES-1010" in e.title for e in ev.ticket_refs)
    pr = next(e for e in ev.ticket_refs if e.kind == "pr")
    assert "agent-nova/SALES-101" in pr.snippet

    pr_paths = {e.title for e in ev.pr_files}
    # PR 7 is for the ticket: every file kept. PR 9: only files matching ticket terms.
    assert "force-app/main/default/classes/TierService.cls" in pr_paths
    assert "force-app/main/default/flows/Account_Tier.flow-meta.xml" in pr_paths
    assert "force-app/main/default/classes/OppCleanup.cls" not in pr_paths
    assert ev.counts()["pr_file"] == 2


@pytest.mark.asyncio
async def test_rate_limit_returns_partial_results():
    rec = Recorder(_routes(), fail={"/search/code": 403})
    search = HttpGitHubSearch(_settings(), transport=httpx.MockTransport(rec))
    ev = await search.gather("SALES-101", "Customer Tier on Account", "Customer_Tier__c")
    assert ev.code == []
    assert ev.ticket_refs
    assert any("code search" in e for e in ev.errors)


@pytest.mark.asyncio
async def test_merged_pr_state():
    routes = _routes()
    routes["/search/issues"]["items"][0].update(
        {"state": "closed", "pull_request": {"merged_at": "2026-09-01T00:00:00Z"}}
    )
    search = HttpGitHubSearch(_settings(), transport=httpx.MockTransport(Recorder(routes)))
    ev = await search.gather("SALES-101", "Customer Tier", "")
    assert any(e.kind == "pr" and e.state == "merged" for e in ev.ticket_refs)


def test_factory_picks_mock_without_token():
    assert isinstance(get_github_search(_settings(github_token="")), MockGitHubSearch)
    assert isinstance(get_github_search(_settings(git_provider="mock")), MockGitHubSearch)
    assert isinstance(get_github_search(_settings()), HttpGitHubSearch)


def test_search_terms_strip_user_story_phrasing():
    _names, keywords = search_terms(
        "As a Sales User, I want to update the existing automatically classify Accounts based "
        "logic on their annual revenue so that I can quickly identify high-value customers."
    )
    assert keywords == ["classify", "Accounts", "annual", "revenue"]
