"""Parser for llms.txt files and link extraction."""

import re
from urllib.parse import urljoin, urlparse

from sensei.types import Domain


def parse_llms_txt_links(content: str, base_url: str) -> list[str]:
	"""Extract all links from an llms.txt file.

	llms.txt files are markdown with:
	- H1 title
	- Blockquote description
	- H2 sections with markdown links

	Args:
	    content: The markdown content of the llms.txt file
	    base_url: The URL of the llms.txt file (for resolving relative links)

	Returns:
	    List of absolute URLs found in the document
	"""
	# Match markdown links: [text](url)
	link_pattern = re.compile(r"\[([^\]]+)\]\(([^)]+)\)")
	links = []

	for match in link_pattern.finditer(content):
		url = match.group(2)
		# Skip anchor-only links
		if url.startswith("#"):
			continue
		# Resolve relative URLs
		absolute_url = urljoin(base_url, url)
		links.append(absolute_url)

	return links


def is_same_domain(base_url: str, target_url: str) -> bool:
	"""Check if target_url is on the same domain as base_url.

	Uses Domain value object for normalization:
	- www.example.com == example.com
	- example.com:443 == example.com
	- EXAMPLE.COM == example.com

	Args:
	    base_url: The reference URL (e.g., llms.txt location)
	    target_url: The URL to check

	Returns:
	    True if both URLs share the same normalized domain
	"""
	return Domain.from_url(base_url) == Domain.from_url(target_url)


def extract_path(url: str) -> str:
	"""Extract the path portion from a URL.

	Args:
	    url: Full URL

	Returns:
	    Path portion (e.g., "/docs/hooks/useState.md")
	"""
	return urlparse(url).path or "/"


def extract_domain(url: str) -> str:
	"""Extract the normalized domain from a URL.

	Args:
	    url: Full URL

	Returns:
	    Normalized domain (e.g., "react.dev")
	"""
	return Domain.from_url(url).value
