# -*- coding: utf-8 -*-
"""论坛帖子页解析 - 复用自 pm001-crawler"""

from __future__ import annotations

import re
from dataclasses import dataclass
from urllib.parse import parse_qs, unquote, urljoin, urlparse

from bs4 import BeautifulSoup


AUTHOR_LINK_PATTERN = re.compile(r"dispuser\.asp\?", re.IGNORECASE)
LEVEL_PATTERN = re.compile(r"交易等级[:：]?\s*([^\n\r]{1,40})")
ADDRESS_PATTERN = re.compile(r"^(?:来自|所在地|地区|地址)[:：]?\s*([^\n\r]{1,60})", re.MULTILINE)


@dataclass(slots=True)
class ThreadPost:
    author_key: str
    author_name: str
    profile_url: str | None
    level: str | None
    address: str | None
    text: str


def parse_thread_posts(
    html: str,
    base_url: str,
    default_author_key: str,
    default_author_name: str,
    default_profile_url: str | None,
) -> list[ThreadPost]:
    """解析帖子页中的回复内容，并提取作者、级别、地址和正文。"""
    soup = BeautifulSoup(html, "lxml")
    posts: list[ThreadPost] = []
    seen_blocks: set[tuple[str, str]] = set()

    for post_layer in soup.find_all("div", class_=lambda c: c and "postlary" in c):
        userinfo = post_layer.find("div", class_="postuserinfo")
        content_div = post_layer.find("div", class_="post")
        if userinfo is None or content_div is None:
            continue

        author_anchor = userinfo.find("a", href=AUTHOR_LINK_PATTERN)
        author_name = None
        author_key = None
        profile_url = None

        if author_anchor:
            author_name = " ".join(author_anchor.stripped_strings).strip()
            author_key = extract_author_key(author_anchor.get("href", ""))
            profile_url = urljoin(base_url, author_anchor.get("href", ""))
        else:
            for div in userinfo.find_all("div", recursive=False):
                text = div.get_text(strip=True)
                if text and len(text) < 30 and "：" not in text and ":" not in text:
                    author_name = text
                    author_key = f"name:{text}"
                    break

        if not author_name:
            author_name = default_author_name
        if not author_key:
            author_key = default_author_key
        if not profile_url:
            profile_url = default_profile_url

        sidebar_text = userinfo.get_text("\n", strip=True)
        content_text = content_div.get_text("\n", strip=True)
        if not content_text:
            continue

        if not sidebar_text:
            continue

        block_key = (author_key, content_text[:120])
        if block_key in seen_blocks:
            continue
        seen_blocks.add(block_key)

        posts.append(
            ThreadPost(
                author_key=author_key,
                author_name=author_name,
                profile_url=profile_url,
                level=extract_level(sidebar_text),
                address=extract_address(sidebar_text) or extract_address(content_text),
                text=content_text,
            )
        )

    if posts:
        return posts

    full_text = soup.get_text("\n", strip=True)
    return [
        ThreadPost(
            author_key=default_author_key,
            author_name=default_author_name,
            profile_url=default_profile_url,
            level=None,
            address=None,
            text=full_text,
        )
    ]


def extract_level(text: str) -> str | None:
    """从作者信息文本中提取等级信息。"""
    match = LEVEL_PATTERN.search(text)
    return match.group(1).strip() if match else None


def extract_address(text: str) -> str | None:
    """从作者信息文本中提取地址信息。"""
    match = ADDRESS_PATTERN.search(text)
    return match.group(1).strip() if match else None


def extract_author_key(href: str) -> str | None:
    """从作者主页链接中提取作者唯一标识。"""
    query = parse_qs(urlparse(href).query)
    if "id" in query and query["id"]:
        return f"id:{query['id'][0]}"
    if "name" in query and query["name"]:
        return f"name:{unquote(query['name'][0])}"
    return None
