"""Shared LinkedIn list-building contract for API capabilities and CLI recipes."""

from __future__ import annotations

from copy import deepcopy
from typing import Any, Dict, List, Tuple


_LINKEDIN_ENDPOINTS: Dict[str, Dict[str, Any]] = {
    "linkedin_status": {
        "method": "GET",
        "path": "/api/integrations/linkedin/status",
        "required_scope": "linkedin:read",
        "notes": "Returns connection status, API mode (classic/sales_navigator), and account metadata.",
    },
    "linkedin_limits": {
        "method": "GET",
        "path": "/api/integrations/linkedin/limits",
        "required_scope": "linkedin:read",
        "notes": "Returns send limits, usage windows, InMail balance, and provider cooldown state.",
    },
    "linkedin_search": {
        "method": "POST",
        "path": "/api/integrations/linkedin/search",
        "required_scope": "linkedin:read",
        "body": {
            "url": "optional LinkedIn/Sales Navigator search URL (overrides keyword filters)",
            "category": "optional people|companies|jobs|posts (default people)",
            "keywords": "optional free-text search",
            "linkedin_api": "optional classic|sales_navigator (default classic)",
            "cursor": "optional pagination cursor",
            "limit": "optional 1-250 (default 25)",
            "extra_params": "optional object with location/industry/company filter IDs",
        },
        "response": {
            "items_field": "items",
            "cursor_field": "cursor",
        },
        "rate_limits": {
            "classic": "~1,000 results/day",
            "sales_navigator": "~2,500 results/day",
            "enforcement": "provider-side; 429/5xx when exceeded",
        },
    },
    "linkedin_search_parameters": {
        "method": "POST",
        "path": "/api/integrations/linkedin/search/parameters",
        "required_scope": "linkedin:read",
        "body": {
            "type": "required: location|industry|company|school|title|language",
            "keywords": "optional search text",
            "limit": "optional 1-250 (default 25)",
        },
        "notes": "Resolve human-readable names to LinkedIn IDs for use in search extra_params.",
    },
    "linkedin_list_posts": {
        "method": "GET",
        "path": "/api/integrations/linkedin/posts/{identifier}",
        "required_scope": "linkedin:read",
        "query": {
            "cursor": "optional pagination cursor",
            "limit": "optional 1-100 (default 25)",
        },
        "notes": "Identifier: profile URL, public ID, or URN.",
    },
    "linkedin_get_post": {
        "method": "GET",
        "path": "/api/integrations/linkedin/posts/{post_id}/detail",
        "required_scope": "linkedin:read",
    },
    "linkedin_post_comments": {
        "method": "GET",
        "path": "/api/integrations/linkedin/posts/{post_id}/comments",
        "required_scope": "linkedin:read",
        "query": {
            "cursor": "optional pagination cursor",
            "limit": "optional 1-100 (default 100)",
        },
    },
    "linkedin_post_reactions": {
        "method": "GET",
        "path": "/api/integrations/linkedin/posts/{post_id}/reactions",
        "required_scope": "linkedin:read",
        "query": {
            "cursor": "optional pagination cursor",
            "limit": "optional 1-100 (default 100)",
        },
    },
}


_LINKEDIN_CAPABILITIES: Dict[str, Any] = {
    "surface_type": "connected_linkedin_search",
    "access_gate": "linkedin_access flag on user",
    "connection_required": True,
    "requires_connected_account": True,
    "api_modes": ["classic", "sales_navigator"],
    "best_for": [
        "replaying a LinkedIn or Sales Navigator search URL",
        "searching LinkedIn-native people, companies, jobs, or posts with a connected account",
        "building engagement lists from LinkedIn posts, comments, or reactions",
    ],
    "not_for": [
        "generic public-web company discovery",
        "provider-hidden semantic people discovery when the source of truth is not specifically LinkedIn",
    ],
    "chooser_guidance": {
        "use_linkedin_when": [
            "the list source of truth is LinkedIn itself",
            "you want to replay a LinkedIn or Sales Navigator search URL",
            "you want comments, reactions, or recent post activity from LinkedIn",
        ],
        "company_first_when": [
            "you need to discover the target accounts before looking for contacts",
        ],
        "people_first_when": [
            "you already know the target companies and want role- or persona-based contacts",
        ],
    },
    "list_building_endpoints": [
        "/api/integrations/linkedin/search",
        "/api/integrations/linkedin/search/parameters",
        "/api/integrations/linkedin/posts/{identifier}",
        "/api/integrations/linkedin/posts/{post_id}/detail",
        "/api/integrations/linkedin/posts/{post_id}/comments",
        "/api/integrations/linkedin/posts/{post_id}/reactions",
    ],
    "rate_limits": {
        "enforcement": "provider-side",
        "search_daily_caps": {
            "classic": "~1,000 results",
            "sales_navigator": "~2,500 results",
        },
    },
    "recommended_cli": [
        "autotouch linkedin status",
        "autotouch linkedin search --keywords 'VP Engineering' --category people",
        "autotouch linkedin recipe --type search",
    ],
}


_LINKEDIN_RECIPES: Dict[str, Dict[str, Any]] = {
    "search": {
        "payload": {
            "category": "people",
            "keywords": "VP Engineering",
            "linkedin_api": "classic",
            "limit": 25,
            "extra_params": {"location": ["103644278"], "industry": ["96"]},
        },
        "usage": "autotouch linkedin search --data-file <payload.json>",
        "notes": [
            "category: people | companies | jobs | posts",
            "linkedin_api: classic | sales_navigator (must match connected account)",
            "Use 'autotouch linkedin search-params' to resolve location/industry IDs",
            "Classic: ~1,000 results/day. Sales Navigator: ~2,500 results/day.",
        ],
    },
    "search_url": {
        "payload": {
            "url": "https://www.linkedin.com/sales/search/people?query=...",
            "linkedin_api": "sales_navigator",
            "limit": 50,
        },
        "usage": "autotouch linkedin search --url 'https://...' --linkedin-api sales_navigator",
        "notes": [
            "Pass a full LinkedIn or Sales Navigator search URL",
            "All filters encoded in the URL are applied automatically",
            "Great for reproducing a saved search from the browser",
        ],
    },
    "search_params": {
        "payload": {"type": "location", "keywords": "San Francisco", "limit": 5},
        "usage": "autotouch linkedin search-params --type location --keywords 'San Francisco'",
        "notes": [
            "Resolve human-readable names to LinkedIn internal IDs",
            "Types: location, industry, company, school, title, language",
            "Pass returned IDs in extra_params of the search payload",
        ],
    },
    "posts": {
        "payload": None,
        "usage": "autotouch linkedin posts --identifier janedoe --limit 10",
        "notes": [
            "Identifier: profile URL, public ID (e.g., janedoe), or URN",
            "Monitor a prospect's recent activity before reaching out",
        ],
    },
    "comments": {
        "payload": None,
        "usage": "autotouch linkedin comments --post-id <POST_ID> --limit 100",
        "notes": [
            "Extract commenters from industry-relevant posts for list building",
            "Combine with reactions for comprehensive engagement-based lists",
        ],
    },
    "reactions": {
        "payload": None,
        "usage": "autotouch linkedin reactions --post-id <POST_ID> --limit 100",
        "notes": [
            "Extract users who reacted to posts for list building",
            "Combine with comments for comprehensive engagement-based lists",
        ],
    },
}


def linkedin_endpoint_entries() -> Dict[str, Dict[str, Any]]:
    return deepcopy(_LINKEDIN_ENDPOINTS)


def linkedin_capabilities_contract() -> Dict[str, Any]:
    return deepcopy(_LINKEDIN_CAPABILITIES)


def linkedin_recipe_types() -> Tuple[str, ...]:
    return tuple(_LINKEDIN_RECIPES.keys())


def linkedin_recipe_entries() -> Dict[str, Dict[str, Any]]:
    return deepcopy(_LINKEDIN_RECIPES)


def linkedin_recipe_entry(recipe_type: str) -> Dict[str, Any] | None:
    recipe = _LINKEDIN_RECIPES.get(str(recipe_type or "").strip())
    return deepcopy(recipe) if isinstance(recipe, dict) else None


__all__ = [
    "linkedin_capabilities_contract",
    "linkedin_endpoint_entries",
    "linkedin_recipe_entries",
    "linkedin_recipe_entry",
    "linkedin_recipe_types",
]
