# 资讯API路由
from fastapi import APIRouter, Depends, HTTPException, Query
from sqlalchemy.orm import Session, joinedload
from typing import List, Optional
from pydantic import BaseModel
from datetime import datetime, date

from app.core.database import get_db
from app.core.auth import get_current_user
from app.models.models import User, Information, Collection

router = APIRouter(prefix="/api/information", tags=["资讯"])


# Schema
class InformationCreate(BaseModel):
    info_type: str  # seek-寻配号, deal-成交数据, publish-发布
    title: str
    content: Optional[str]
    collection_id: Optional[str] = None
    expect_category: Optional[str] = None
    expect_version: Optional[str] = None
    expect_packaging: Optional[str] = None
    expect_number: Optional[str] = None
    expect_price_min: Optional[float] = None
    expect_price_max: Optional[float] = None
    deal_price: Optional[float] = None
    deal_date: Optional[date] = None


class InformationUpdate(BaseModel):
    title: Optional[str] = None
    content: Optional[str]
    status: Optional[str] = None
    expect_category: Optional[str] = None
    expect_version: Optional[str] = None
    expect_packaging: Optional[str] = None
    expect_number: Optional[str] = None
    expect_price_min: Optional[float] = None
    expect_price_max: Optional[float] = None
    deal_price: Optional[float] = None
    deal_date: Optional[date] = None


class InformationResponse(BaseModel):
    id: str
    user_id: str
    info_type: str
    title: str
    content: Optional[str]
    collection_id: Optional[str]
    expect_category: Optional[str]
    expect_version: Optional[str]
    expect_packaging: Optional[str]
    expect_number: Optional[str]
    expect_price_min: Optional[float]
    expect_price_max: Optional[float]
    deal_price: Optional[float]
    deal_date: Optional[date]
    status: str
    is_matched: Optional[str] = "pending"
    matched_user_id: Optional[str] = None
    matched_contact: Optional[str] = None
    view_count: int
    contact_count: int
    created_at: datetime
    # 用户信息
    user_name: Optional[str] = None
    user_avatar: Optional[str] = None
    # 关联藏品信息
    collection_name: Optional[str] = None
    collection_category: Optional[str] = None
    collection_version: Optional[str] = None
    collection_number: Optional[str] = None
    # 匹配数量（我的藏品中满足条件的数量）
    matched_count: Optional[int] = 0

    class Config:
        from_attributes = True


# 资讯列表
@router.get("/list", response_model=List[InformationResponse])
def get_information_list(
    info_type: Optional[str] = Query(None, description="类型: seek/deal/publish"),
    status: str = Query("active", description="状态: active/closed/expired"),
    page: int = Query(1, ge=1),
    page_size: int = Query(20, ge=1, le=100),
    current_user: Optional[User] = Depends(get_current_user),
    db: Session = Depends(get_db)
):
    """获取资讯列表（公开，无需登录）"""
    query = db.query(Information).options(
        joinedload(Information.user),
        joinedload(Information.collection)
    ).filter(Information.status == status)
    
    if info_type:
        query = query.filter(Information.info_type == info_type)
    
    # 按创建时间倒序
    query = query.order_by(Information.created_at.desc())
    
    # 分页
    offset = (page - 1) * page_size
    items = query.offset(offset).limit(page_size).all()
    
    # 转换结果
    result = []
    for item in items:
        # 计算匹配数量（仅对seek类型，且用户登录时）
        matched_count = 0
        if item.info_type == 'seek' and item.expect_number and current_user:
            matched_count = match_collections_count(db, current_user.f99_90_id, item.expect_number)
        
        result.append(InformationResponse(
            id=item.id,
            user_id=item.user_id,
            info_type=item.info_type,
            title=item.title,
            content=item.content,
            collection_id=item.collection_id,
            expect_category=item.expect_category,
            expect_version=item.expect_version,
            expect_packaging=item.expect_packaging,
            expect_number=item.expect_number,
            expect_price_min=item.expect_price_min,
            expect_price_max=item.expect_price_max,
            deal_price=item.deal_price,
            deal_date=item.deal_date,
            status=item.status,
            is_matched=item.is_matched,
            matched_user_id=item.matched_user_id,
            matched_contact=item.matched_contact,
            view_count=item.view_count,
            contact_count=item.contact_count,
            created_at=item.created_at,
            user_name=item.user.f01_01_name if item.user else None,
            user_avatar=item.user.avatar if item.user else None,
            collection_name=item.collection.f01_01_name if item.collection else None,
            collection_category=item.collection.f01_03_category if item.collection else None,
            collection_version=item.collection.f02_11_version if item.collection else None,
            collection_number=item.collection.f02_10_prefix_serial if item.collection else None,
            matched_count=matched_count,
        ))
    
    return result


def match_collections_count(db: Session, user_id: str, expect_number: str) -> int:
    """根据号码特征计算匹配藏品数量"""
    if not expect_number or len(expect_number) != 10:
        return 0
    
    # 固定前缀
    if not expect_number.startswith('J0'):
        return 0
    
    pattern = expect_number[2:]  # 后8位
    if not pattern:
        return 0
    
    # 获取用户所有藏品
    collections = db.query(Collection).filter(
        Collection.f99_91_user_id == user_id,
        Collection.f01_04_status == "in_collection"
    ).all()
    
    count = 0
    for c in collections:
        number = c.f02_10_prefix_serial or ''
        # 去掉J0前缀后取前8位
        if len(number) >= 10 and number.startswith('J0'):
            col_pattern = number[2:10]
            if match_pattern(col_pattern, pattern):
                count += 1
        elif len(number) >= 8:
            col_pattern = number[:8]
            if match_pattern(col_pattern, pattern):
                count += 1
    
    return count


def match_pattern(col_number: str, pattern: str) -> bool:
    """匹配号码特征模式"""
    # X = 任意数字
    # A = 非4
    # B = 非47
    # C = 非347
    # D = 非247
    # E = 非2347
    # F = 非23457
    # G = 非123457
    
    # 注意：col_number已经是去掉J0前缀后的8位号码，不需要再处理
    col_num = col_number
    
    for i, p in enumerate(pattern):
        if i >= len(col_num):
            return False
        
        c = col_num[i]
        
        if p == 'X':
            if not c.isdigit():
                return False
        elif p == 'A':
            if c == '4':
                return False
        elif p == 'B':
            if c in '47':
                return False
        elif p == 'C':
            if c in '347':
                return False
        elif p == 'D':
            if c in '247':
                return False
        elif p == 'E':
            if c in '2347':
                return False
        elif p == 'F':
            if c in '23457':
                return False
        elif p == 'G':
            if c in '123457':
                return False
        else:
            # 数字或字母必须完全匹配
            if p != c:
                return False
    
    return True


# 获取单条资讯
@router.get("/{info_id}", response_model=InformationResponse)
def get_information(
    info_id: str,
    db: Session = Depends(get_db)
):
    """获取资讯详情"""
    item = db.query(Information).options(
        joinedload(Information.user),
        joinedload(Information.collection)
    ).filter(Information.id == info_id).first()
    
    if not item:
        raise HTTPException(status_code=404, detail="资讯不存在")
    
    # 增加浏览次数
    item.view_count += 1
    db.commit()
    
    return InformationResponse(
        id=item.id,
        user_id=item.user_id,
        info_type=item.info_type,
        title=item.title,
        content=item.content,
        collection_id=item.collection_id,
        expect_category=item.expect_category,
        expect_version=item.expect_version,
        expect_packaging=item.expect_packaging,
        expect_number=item.expect_number,
        expect_price_min=item.expect_price_min,
        expect_price_max=item.expect_price_max,
        deal_price=item.deal_price,
        deal_date=item.deal_date,
        status=item.status,
        view_count=item.view_count,
        contact_count=item.contact_count,
        created_at=item.created_at,
        user_name=item.user.f01_01_name if item.user else None,
        user_avatar=item.user.avatar if item.user else None,
        collection_name=item.collection.f01_01_name if item.collection else None,
        collection_category=item.collection.f01_03_category if item.collection else None,
        collection_version=item.collection.f02_11_version if item.collection else None,
        collection_number=item.collection.f02_10_prefix_serial if item.collection else None,
    )


# 发布资讯
@router.post("/", response_model=InformationResponse)
def create_information(
    data: InformationCreate,
    current_user: User = Depends(get_current_user),
    db: Session = Depends(get_db)
):
    """发布资讯"""
    info = Information(
        user_id=current_user.f99_90_id,
        info_type=data.info_type,
        title=data.title,
        content=data.content,
        collection_id=data.collection_id,
        expect_category=data.expect_category,
        expect_version=data.expect_version,
        expect_packaging=data.expect_packaging,
        expect_number=data.expect_number,
        expect_price_min=data.expect_price_min,
        expect_price_max=data.expect_price_max,
        deal_price=data.deal_price,
        deal_date=data.deal_date,
        status="active"
    )
    db.add(info)
    db.commit()
    db.refresh(info)
    
    return InformationResponse(
        id=info.id,
        user_id=info.user_id,
        info_type=info.info_type,
        title=info.title,
        content=info.content,
        collection_id=info.collection_id,
        expect_category=info.expect_category,
        expect_version=info.expect_version,
        expect_packaging=info.expect_packaging,
        expect_number=info.expect_number,
        expect_price_min=info.expect_price_min,
        expect_price_max=info.expect_price_max,
        deal_price=info.deal_price,
        deal_date=info.deal_date,
        status=info.status,
        view_count=info.view_count,
        contact_count=info.contact_count,
        created_at=info.created_at,
        user_name=current_user.f01_01_name,
        user_avatar=current_user.avatar,
        collection_name=None,
        collection_category=None,
        collection_version=None,
        collection_number=None,
    )


# 更新资讯
@router.put("/{info_id}", response_model=InformationResponse)
def update_information(
    info_id: str,
    data: InformationUpdate,
    current_user: User = Depends(get_current_user),
    db: Session = Depends(get_db)
):
    """更新资讯"""
    info = db.query(Information).filter(
        Information.id == info_id,
        Information.user_id == current_user.f99_90_id
    ).first()
    
    if not info:
        raise HTTPException(status_code=404, detail="资讯不存在或无权修改")
    
    # 更新字段
    if data.title is not None:
        info.title = data.title
    if data.content is not None:
        info.content = data.content
    if data.status is not None:
        info.status = data.status
    if data.expect_category is not None:
        info.expect_category = data.expect_category
    if data.expect_version is not None:
        info.expect_version = data.expect_version
    if data.expect_packaging is not None:
        info.expect_packaging = data.expect_packaging
    if data.expect_number is not None:
        info.expect_number = data.expect_number
    if data.expect_price_min is not None:
        info.expect_price_min = data.expect_price_min
    if data.expect_price_max is not None:
        info.expect_price_max = data.expect_price_max
    if data.deal_price is not None:
        info.deal_price = data.deal_price
    if data.deal_date is not None:
        info.deal_date = data.deal_date
    
    db.commit()
    db.refresh(info)
    
    return InformationResponse(
        id=info.id,
        user_id=info.user_id,
        info_type=info.info_type,
        title=info.title,
        content=info.content,
        collection_id=info.collection_id,
        expect_category=info.expect_category,
        expect_version=info.expect_version,
        expect_packaging=info.expect_packaging,
        expect_number=info.expect_number,
        expect_price_min=info.expect_price_min,
        expect_price_max=info.expect_price_max,
        deal_price=info.deal_price,
        deal_date=info.deal_date,
        status=info.status,
        view_count=info.view_count,
        contact_count=info.contact_count,
        created_at=info.created_at,
        user_name=current_user.f01_01_name,
        user_avatar=current_user.avatar,
        collection_name=info.collection.f01_01_name if info.collection else None,
        collection_category=info.collection.f01_03_category if info.collection else None,
        collection_version=info.collection.f02_11_version if info.collection else None,
        collection_number=info.collection.f02_10_prefix_serial if info.collection else None,
    )


# 删除资讯
@router.delete("/{info_id}")
def delete_information(
    info_id: str,
    current_user: User = Depends(get_current_user),
    db: Session = Depends(get_db)
):
    """删除资讯"""
    # 允许admin删除任何人的资讯
    if current_user.role == "admin":
        info = db.query(Information).filter(Information.id == info_id).first()
    else:
        info = db.query(Information).filter(
            Information.id == info_id,
            Information.user_id == current_user.f99_90_id
        ).first()
    
    if not info:
        raise HTTPException(status_code=404, detail="资讯不存在或无权删除")
    
    db.delete(info)
    db.commit()
    
    return {"message": "删除成功"}


# 寻配号 - 自动匹配推荐藏品
@router.get("/seek/match")
def get_seek_match(
    info_id: str,
    current_user: Optional[User] = Depends(get_current_user),
    db: Session = Depends(get_db)
):
    """获取符合条件的我的藏品推荐"""
    if not current_user:
        raise HTTPException(status_code=401, detail="请先登录")
    
    info = db.query(Information).filter(
        Information.id == info_id,
        Information.info_type == "seek"
    ).first()
    
    if not info:
        raise HTTPException(status_code=404, detail="寻配号信息不存在")
    
    # 更新用户配号(寻号)次数
    current_user.f99_96_search_count = (current_user.f99_96_search_count or 0) + 1
    db.commit()
    
    # 获取用户所有藏品
    collections = db.query(Collection).filter(
        Collection.f99_91_user_id == current_user.f99_90_id,
        Collection.f01_04_status == "in_collection"
    ).all()
    
    # 去掉版别筛选，因为藏品分类和发布需求的版别不同
    # if info.expect_category:
    #     collections = [c for c in collections if c.f01_03_category == info.expect_category]
    
    # 按号码特征模式匹配
    matched = []
    if info.expect_number and len(info.expect_number) == 10:
        pattern = info.expect_number[2:]  # 后8位
        for c in collections:
            number = c.f02_10_prefix_serial or ''
            # 去掉J0前缀后取前8位
            if len(number) >= 10 and number.startswith('J0'):
                col_pattern = number[2:10]  # 取J0后面的8位
                if match_pattern(col_pattern, pattern):
                    matched.append(c)
            elif len(number) >= 8:
                col_pattern = number[:8]  # 取前8位
                if match_pattern(col_pattern, pattern):
                    matched.append(c)
    else:
        matched = collections
    
    return {
        "info_id": info_id,
        "matched_count": len(matched),
        "collections": [
            {
                "id": c.f99_90_id,
                "code": c.f01_02_code or '',
                "name": c.f01_01_name,
                "number": c.f02_10_prefix_serial,
                "status": c.f01_04_status,
                "category": c.f01_03_category,
                "version": c.f02_11_version,
                "packaging": c.f02_12_packaging,
                "cost_price": c.f05_40_cost_price,
            }
            for c in matched
        ]
    }


# 我的寻号列表
@router.get("/my-seeks")
def get_my_seeks(
    current_user: Optional[User] = Depends(get_current_user),
    db: Session = Depends(get_db)
):
    """获取当前用户发布的所有寻号信息"""
    if not current_user:
        raise HTTPException(status_code=401, detail="请先登录")
    
    items = db.query(Information).filter(
        Information.user_id == current_user.f99_90_id,
        Information.info_type == "seek",
        Information.status == "active"
    ).order_by(Information.created_at.desc()).all()
    
    result = []
    for item in items:
        # 计算匹配数量
        matched_count = 0
        if item.expect_number:
            matched_count = match_collections_count(db, current_user.f99_90_id, item.expect_number)
        
        result.append(InformationResponse(
            id=item.id,
            user_id=item.user_id,
            info_type=item.info_type,
            title=item.title,
            content=item.content,
            collection_id=item.collection_id,
            expect_category=item.expect_category,
            expect_version=item.expect_version,
            expect_packaging=item.expect_packaging,
            expect_number=item.expect_number,
            expect_price_min=item.expect_price_min,
            expect_price_max=item.expect_price_max,
            deal_price=item.deal_price,
            deal_date=item.deal_date,
            status=item.status,
            is_matched=item.is_matched,
            matched_user_id=item.matched_user_id,
            matched_contact=item.matched_contact,
            view_count=item.view_count,
            contact_count=item.contact_count,
            created_at=item.created_at,
            user_name=item.user.f01_01_name if item.user else None,
            user_avatar=item.user.avatar if item.user else None,
            collection_name=item.collection.f01_01_name if item.collection else None,
            collection_category=item.collection.f01_03_category if item.collection else None,
            collection_version=item.collection.f02_11_version if item.collection else None,
            collection_number=item.collection.f02_10_prefix_serial if item.collection else None,
            matched_count=matched_count,
        ))
    
    return result


# 成交数据统计
@router.get("/deal/stats")
def get_deal_stats(
    days: int = Query(7, ge=1, le=90, description="统计天数"),
    db: Session = Depends(get_db)
):
    """获取成交数据统计"""
    from sqlalchemy import func
    from datetime import timedelta
    
    start_date = datetime.now() - timedelta(days=days)
    
    # 按版别统计
    by_version = db.query(
        Information.expect_version,
        func.count(Information.id).label("count"),
        func.avg(Information.deal_price).label("avg_price"),
        func.max(Information.deal_price).label("max_price"),
        func.min(Information.deal_price).label("min_price")
    ).filter(
        Information.info_type == "deal",
        Information.status == "active",
        Information.created_at >= start_date
    ).group_by(Information.expect_version).all()
    
    # 按包装统计
    by_packaging = db.query(
        Information.expect_packaging,
        func.count(Information.id).label("count"),
        func.avg(Information.deal_price).label("avg_price")
    ).filter(
        Information.info_type == "deal",
        Information.status == "active",
        Information.created_at >= start_date
    ).group_by(Information.expect_packaging).all()
    
    # 按号码分类统计
    by_number = db.query(
        Information.expect_number,
        func.count(Information.id).label("count"),
        func.avg(Information.deal_price).label("avg_price")
    ).filter(
        Information.info_type == "deal",
        Information.status == "active",
        Information.expect_number.isnot(None),
        Information.created_at >= start_date
    ).group_by(Information.expect_number).all()
    
    return {
        "days": days,
        "by_version": [
            {"version": r[0] or "未知", "count": r[1], "avg_price": float(r[2] or 0), "max_price": float(r[3] or 0), "min_price": float(r[4] or 0)}
            for r in by_version if r[0]
        ],
        "by_packaging": [
            {"packaging": r[0] or "未知", "count": r[1], "avg_price": float(r[2] or 0)}
            for r in by_packaging if r[0]
        ],
        "by_number": [
            {"number": r[0], "count": r[1], "avg_price": float(r[2] or 0)}
            for r in by_number
        ]
    }


# 获取我的发布列表
@router.get("/my/list", response_model=List[InformationResponse])
def get_my_information_list(
    page: int = Query(1, ge=1),
    page_size: int = Query(20, ge=1, le=100),
    current_user: User = Depends(get_current_user),
    db: Session = Depends(get_db)
):
    """获取我的发布列表"""
    items = db.query(Information).options(
        joinedload(Information.collection)
    ).filter(
        Information.user_id == current_user.f99_90_id
    ).order_by(Information.created_at.desc()).offset((page-1)*page_size).limit(page_size).all()
    
    result = []
    for item in items:
        result.append(InformationResponse(
            id=item.id,
            user_id=item.user_id,
            info_type=item.info_type,
            title=item.title,
            content=item.content,
            collection_id=item.collection_id,
            expect_category=item.expect_category,
            expect_version=item.expect_version,
            expect_packaging=item.expect_packaging,
            expect_number=item.expect_number,
            expect_price_min=item.expect_price_min,
            expect_price_max=item.expect_price_max,
            deal_price=item.deal_price,
            deal_date=item.deal_date,
            status=item.status,
            is_matched=item.is_matched,
            matched_user_id=item.matched_user_id,
            matched_contact=item.matched_contact,
            view_count=item.view_count,
            contact_count=item.contact_count,
            created_at=item.created_at,
            user_name=current_user.f01_01_name,
            user_avatar=current_user.avatar,
            collection_name=item.collection.f01_01_name if item.collection else None,
            collection_category=item.collection.f01_03_category if item.collection else None,
            collection_version=item.collection.f02_11_version if item.collection else None,
            collection_number=item.collection.f02_10_prefix_serial if item.collection else None,
        ))
    
    return result

# ============ 获取当前用户发布的列表 ============
@router.get("/my")
def get_my_information(
    page: int = Query(1, ge=1),
    limit: int = Query(20, ge=1, le=100),
    current_user: User = Depends(get_current_user),
    db: Session = Depends(get_db)
):
    """获取当前用户发布的信息列表"""
    total = db.query(Information).filter(Information.author == current_user.f01_01_name).count()
    infos = db.query(Information).filter(
        Information.author == current_user.f01_01_name
    ).order_by(Information.created_at.desc()).offset((page-1)*limit).limit(limit).all()
    
    return {
        "total": total,
        "list": [{
            "id": i.id,
            "title": i.title,
            "content": i.content,
            "info_type": i.info_type,
            "author": i.author,
            "created_at": i.created_at.isoformat() if i.created_at else None
        } for i in infos]
    }


# ============ 匹配寻号 ============
class MatchSeekRequest(BaseModel):
    info_id: str
    collection_id: Optional[str] = None
    contact: Optional[str] = None


@router.post("/seek/match-confirm")
def match_seek(
    request: MatchSeekRequest,
    current_user: User = Depends(get_current_user),
    db: Session = Depends(get_db)
):
    """确认匹配寻号 - 用户愿意交换联系方式给发布者"""
    info = db.query(Information).filter(
        Information.id == request.info_id,
        Information.info_type == "seek",
        Information.status == "active"
    ).first()
    
    if not info:
        raise HTTPException(status_code=404, detail="寻配号信息不存在")
    
    # 检查是否已被匹配（一个寻号只能被一个用户匹配）
    if info.is_matched == "matched":
        raise HTTPException(status_code=400, detail="该寻号已被其他用户匹配")
    
    # 更新匹配状态
    info.is_matched = "matched"
    info.matched_user_id = current_user.f99_90_id
    # 保存匹配者的联系方式
    info.matched_contact = request.contact or ''
    
    # 更新发布寻号者的内容，显示有藏品被匹配
    original_content = info.content or ""
    # 添加匹配信息：藏品被XX藏友匹配，联系方式为：xxx
    match_info = f"\n藏品被{current_user.f01_01_name}匹配成功！联系方式：{request.collection_id or '已交换'}"
    info.content = original_content + match_info
    
    db.commit()
    
    return {"message": "匹配成功，已通知发布者", "is_matched": "matched"}


# ============ 添加留言 ============
class CommentRequest(BaseModel):
    information_id: str
    content: str


@router.post("/comment")
def add_comment(
    request: CommentRequest,
    current_user: User = Depends(get_current_user),
    db: Session = Depends(get_db)
):
    """添加留言"""
    info = db.query(Information).filter(
        Information.id == request.information_id
    ).first()
    
    if not info:
        raise HTTPException(status_code=404, detail="资讯不存在")
    
    # 创建留言
    from app.models.models import InformationComment
    comment = InformationComment(
        information_id=request.information_id,
        user_id=current_user.f99_90_id,
        content=request.content
    )
    db.add(comment)
    db.commit()
    
    return {
        "message": "留言成功",
        "comment": {
            "id": comment.id,
            "content": comment.content,
            "user_name": current_user.f01_01_name,
            "user_avatar": current_user.avatar,
            "created_at": comment.created_at
        }
    }


# ============ 获取评论列表 ============
@router.get("/comments/{information_id}")
def get_comments(
    information_id: str,
    db: Session = Depends(get_db)
):
    """获取资讯的评论列表"""
    from app.models.models import InformationComment
    comments = db.query(InformationComment).filter(
        InformationComment.information_id == information_id
    ).order_by(InformationComment.created_at.desc()).all()
    
    return [
        {
            "id": c.id,
            "content": c.content,
            "user_name": c.user.f01_01_name if c.user else '匿名用户',
            "user_avatar": c.user.avatar if c.user else None,
            "created_at": c.created_at
        }
        for c in comments
    ]


# ============ 获取匹配者信息 ============
@router.get("/seek/matched-user/{info_id}")
def get_matched_user(
    info_id: str,
    current_user: User = Depends(get_current_user),
    db: Session = Depends(get_db)
):
    """获取寻号的匹配者信息（仅发布者可见）"""
    info = db.query(Information).filter(
        Information.id == info_id,
        Information.info_type == "seek"
    ).first()
    
    if not info:
        raise HTTPException(status_code=404, detail="寻配号信息不存在")
    
    # 只有发布者可以看到匹配者信息
    if info.user_id != current_user.f99_90_id:
        raise HTTPException(status_code=403, detail="无权访问")
    
    if not info.matched_user_id:
        return {"message": "暂无匹配者"}
    
    # 获取匹配者信息
    matched_user = db.query(User).filter(User.f99_90_id == info.matched_user_id).first()
    if not matched_user:
        return {"message": "匹配者不存在"}
    
    return {
        "matched_user_id": info.matched_user_id,
        "user_name": matched_user.f01_01_name,
        "phone": matched_user.phone,
        "matched_contact": info.matched_contact,
        "matched_at": info.updated_at.isoformat() if info.updated_at else None
    }


# ============ 获取发布者信息 ============
@router.get("/seek/publisher/{info_id}")
def get_publisher_info(
    info_id: str,
    current_user: User = Depends(get_current_user),
    db: Session = Depends(get_db)
):
    """获取寻号的发布者信息（仅匹配者可见）"""
    info = db.query(Information).filter(
        Information.id == info_id,
        Information.info_type == "seek"
    ).first()
    
    if not info:
        raise HTTPException(status_code=404, detail="寻配号信息不存在")
    
    # 只有匹配者可以看到发布者信息
    if not info.matched_user_id or info.matched_user_id != current_user.f99_90_id:
        raise HTTPException(status_code=403, detail="无权访问")
    
    # 获取发布者信息
    publisher = db.query(User).filter(User.f99_90_id == info.user_id).first()
    if not publisher:
        return {"message": "发布者不存在"}
    
    # 从content中解析联系方式
    contact = ''
    if info.content:
        import re
        match = re.search(r'联系方式[:\s]*(.+?)(?:\n|$)', info.content)
        if match:
            contact = match.group(1).strip()
    
    return {
        "user_id": info.user_id,
        "user_name": publisher.f01_01_name,
        "phone": publisher.phone,
        "contact": contact,
        "created_at": info.created_at.isoformat() if info.created_at else None
    }


@router.get("/yichen-posts")
def get_yichen_posts(category: str = None, search: str = None, page: int = 1, page_size: int = 20):
    from app.models.models import Information
    from sqlalchemy import desc
    query = db.query(Information).filter(Information.info_type == 'yichen')
    if category:
        query = query.filter(Information.expect_category == category)
    if search:
        query = query.filter(Information.title.contains(search))
    total = query.count()
    offset = (page - 1) * page_size
    items = query.order_by(desc(Information.created_at)).offset(offset).limit(page_size).all()
    return {"data": items, "pagination": {"page": page, "limit": page_size, "total": total}}
