# Copyright (c) DevSecCode. All rights reserved.
# Licensed under the MIT License. See License.txt in the project root.

"""RSS feed connector — fetch and filter RSS/Atom feeds."""

from __future__ import annotations

from typing import Any

import httpx

from dsc_api.connectors.base import BaseConnector, ConnectorParam
from dsc_api.connectors.sdk import connector, action


@connector(
	id='rss',
	name='RSS Feed',
	description='Fetch and filter RSS/Atom feeds',
	icon='rss',
	auth_type='none',
)
class RssConnector(BaseConnector):

	async def test_connection(self) -> bool:
		return True

	@action(
		id='fetch_feed',
		name='Fetch Feed',
		description='Fetch entries from an RSS/Atom feed URL',
		params=[
			ConnectorParam(name='url', type='string', required=True, label='Feed URL'),
			ConnectorParam(name='limit', type='number', default=20, label='Max Entries'),
		],
	)
	async def fetch_feed(self, url: str = '', limit: int = 20, **kw: Any) -> list[dict[str, Any]]:
		try:
			import feedparser
		except ImportError:
			return [{'error': 'feedparser not installed. Install with: pip install "dsc-api[connectors]"'}]

		async with httpx.AsyncClient() as client:
			resp = await client.get(url, timeout=15, follow_redirects=True)

		feed = feedparser.parse(resp.text)
		entries = []
		for entry in feed.entries[:limit]:
			entries.append({
				'title': getattr(entry, 'title', ''),
				'link': getattr(entry, 'link', ''),
				'published': getattr(entry, 'published', ''),
				'summary': getattr(entry, 'summary', '')[:500],
				'author': getattr(entry, 'author', ''),
			})
		return entries

	@action(
		id='filter_entries',
		name='Filter Entries',
		description='Fetch and filter feed entries by keyword',
		params=[
			ConnectorParam(name='url', type='string', required=True, label='Feed URL'),
			ConnectorParam(name='keyword', type='string', required=True, label='Filter Keyword'),
			ConnectorParam(name='limit', type='number', default=20, label='Max Entries'),
		],
	)
	async def filter_entries(self, url: str = '', keyword: str = '', limit: int = 20, **kw: Any) -> list[dict[str, Any]]:
		all_entries = await self.fetch_feed(url=url, limit=limit * 2)
		if not keyword:
			return all_entries[:limit]
		kw_lower = keyword.lower()
		return [
			e for e in all_entries
			if kw_lower in e.get('title', '').lower() or kw_lower in e.get('summary', '').lower()
		][:limit]
