"""Stub verification runners for Autopilot."""

from __future__ import annotations

from dataclasses import dataclass
from pathlib import Path

from g_gremlin.scout.engine import ScoutEngine
from g_gremlin.scout.loader import load_scan_config
from g_gremlin.scout.models import ScoutFinding

from .contracts import PlanStep, PlanV1
from .policy import AutonomyPolicy
from .tools import AutopilotToolDefinition, ToolRegistry


@dataclass
class CheckResult:
    check_name: str
    passed: bool
    detail: str = ""


def _resolve_check_names(step: PlanStep, tool_def: AutopilotToolDefinition | None) -> list[str]:
    if step.prechecks:
        return list(step.prechecks)
    if tool_def and tool_def.default_prechecks:
        return list(tool_def.default_prechecks)
    return []


def _resolve_postcheck_names(step: PlanStep, tool_def: AutopilotToolDefinition | None) -> list[str]:
    if step.postchecks:
        return list(step.postchecks)
    if tool_def and tool_def.default_postchecks:
        return list(tool_def.default_postchecks)
    return []


def run_prechecks(step: PlanStep, tool_def: AutopilotToolDefinition | None) -> list[CheckResult]:
    return [CheckResult(check_name=name, passed=True) for name in _resolve_check_names(step, tool_def)]


def run_postchecks(step: PlanStep, tool_def: AutopilotToolDefinition | None) -> list[CheckResult]:
    return [CheckResult(check_name=name, passed=True) for name in _resolve_postcheck_names(step, tool_def)]


def run_verification(
    plan: PlanV1,
    registry: ToolRegistry,
    *,
    policy: AutonomyPolicy | None = None,
    state_dir: Path | None = None,
    config_path: Path | None = None,
) -> dict[str, str]:
    if policy and not policy.defaults.verify_after_execute:
        return {}

    scout_names = list(plan.verification or [])
    if not scout_names:
        return {}

    scan_cfg = load_scan_config(config_path)
    crm = (scan_cfg.crm or "salesforce").lower()
    org_alias = policy.org_alias if policy else scan_cfg.org_alias

    engine = ScoutEngine(user_credentials=_get_user_credentials())
    results: dict[str, str] = {}
    for scout_name in scout_names:
        try:
            params = (scan_cfg.per_scout_params or {}).get(scout_name, {})
            finding = engine.run_scout(
                scout_name,
                params=params,
                top_n=scan_cfg.top_n,
                org_alias=org_alias,
                crm=crm,
                hubspot_profile=scan_cfg.hubspot_profile,
                dynamics_profile=scan_cfg.dynamics_profile,
            )
            results[scout_name] = _verification_status(finding)
        except Exception:
            results[scout_name] = "fail"
    return results


def _verification_status(finding: ScoutFinding) -> str:
    if finding.status == "unsupported":
        return "partial"
    if finding.status == "error":
        return "fail"
    if finding.findings_count > 0 or finding.status == "findings":
        return "fail"
    return "pass"


def _get_user_credentials() -> set[str]:
    try:
        from g_gremlin.credentials.provider import CredentialProvider

        provider = CredentialProvider()
        return set(provider.list_configured_integrations())
    except Exception:
        return set()


__all__ = [
    "CheckResult",
    "run_prechecks",
    "run_postchecks",
    "run_verification",
]
