package model

import (
	"database/sql/driver"
	"encoding/json"
	"errors"
	"time"
)

// ParsingConfig 解析配置
type ParsingConfig struct {
	Engine     string `json:"engine"`      // markitdown / docling
	DoclingURL string `json:"docling_url"`  // Docling 服务 URL
	EnablePDF  bool   `json:"enable_pdf"`   // 是否启用 PDF 解析
	Pandoc     bool   `json:"pandoc"`      // 是否启用 Pandoc
}

// Scan 实现 sql.Scanner 接口
func (p *ParsingConfig) Scan(value interface{}) error {
	if value == nil {
		return nil
	}
	bytes, ok := value.([]byte)
	if !ok {
		return errors.New("type assertion to []byte failed")
	}
	return json.Unmarshal(bytes, p)
}

// Value 实现 driver.Valuer 接口
func (p ParsingConfig) Value() (driver.Value, error) {
	return json.Marshal(p)
}

// StorageConfig 存储配置
type StorageConfig struct {
	Type            string `json:"type"`             // local / minio / s3
	Endpoint        string `json:"endpoint"`         // MinIO/S3 endpoint
	Bucket          string `json:"bucket"`           // MinIO/S3 bucket
	AccessKeyID     string `json:"access_key_id"`   // MinIO/S3 access key
	SecretAccessKey string `json:"secret_access_key"` // MinIO/S3 secret key
	UseSSL          bool   `json:"use_ssl"`         // MinIO/S3 use SSL
}

// Scan 实现 sql.Scanner 接口
func (s *StorageConfig) Scan(value interface{}) error {
	if value == nil {
		return nil
	}
	bytes, ok := value.([]byte)
	if !ok {
		return errors.New("type assertion to []byte failed")
	}
	return json.Unmarshal(bytes, s)
}

// Value 实现 driver.Valuer 接口
func (s StorageConfig) Value() (driver.Value, error) {
	return json.Marshal(s)
}

// KnowledgeBase 知识库
type KnowledgeBase struct {
	ID               string         `json:"id" gorm:"primaryKey;type:varchar(36)"`
	Name             string         `json:"name" gorm:"type:varchar(255);not null"`
	Description      string         `json:"description" gorm:"type:text"`
	LLMModelID       string         `json:"llm_model_id" gorm:"type:varchar(36);not null"`
	EmbeddingModelID string         `json:"embedding_model_id" gorm:"type:varchar(36);not null"`
	ParsingConfig    ParsingConfig  `json:"parsing_config" gorm:"type:json"`
	StorageConfig    StorageConfig  `json:"storage_config" gorm:"type:json"` // 存储配置
	Status           string         `json:"status" gorm:"type:varchar(20);default:active"` // active / inactive
	DocumentCount    int            `json:"document_count" gorm:"default:0"`
	ChunkCount       int            `json:"chunk_count" gorm:"default:0"`
	CreatedAt        time.Time      `json:"created_at"`
	UpdatedAt        time.Time      `json:"updated_at"`
}

func (KnowledgeBase) TableName() string {
	return "knowledge_base"
}

// KnowledgeDocument 知识库文档
type KnowledgeDocument struct {
	ID               string    `json:"id" gorm:"primaryKey;type:varchar(36)"`
	KnowledgeBaseID string    `json:"knowledge_base_id" gorm:"type:varchar(36);not null;index"`
	Name             string    `json:"name" gorm:"type:varchar(255);not null"`
	FileKey          string    `json:"file_key" gorm:"type:varchar(500)"`
	FileURL          string    `json:"file_url" gorm:"type:varchar(500)"`  // 文件访问 URL
	FileSize         int64     `json:"file_size" gorm:"type:bigint;default:0"`
	Content          string    `json:"content" gorm:"type:longtext"`        // Markdown 内容（AI-Core 解析结果）
	Status           string    `json:"status" gorm:"type:varchar(20);default:parsing"` // parsing / parsed / failed
	ChunkCount       int       `json:"chunk_count" gorm:"default:0"`
	UploadedAt       time.Time `json:"uploaded_at"`
}

func (KnowledgeDocument) TableName() string {
	return "knowledge_document"
}

// ========== Request/Response ==========

// CreateKnowledgeRequest 创建知识库请求
type CreateKnowledgeRequest struct {
	Name             string         `json:"name" binding:"required"`
	Description      string         `json:"description"`
	LLMModelID       string         `json:"llm_model_id" binding:"required"`
	EmbeddingModelID string         `json:"embedding_model_id" binding:"required"`
	ParsingConfig    ParsingConfig  `json:"parsing_config" binding:"required"`
	StorageConfig    StorageConfig  `json:"storage_config"` // 存储配置，不传则使用全局配置
}

// UpdateKnowledgeRequest 更新知识库请求
type UpdateKnowledgeRequest struct {
	Name             string         `json:"name"`
	Description      string         `json:"description"`
	LLMModelID       string         `json:"llm_model_id"`
	EmbeddingModelID string         `json:"embedding_model_id"`
	ParsingConfig    ParsingConfig  `json:"parsing_config"`
	StorageConfig    StorageConfig  `json:"storage_config"`
	Status           string         `json:"status"`
}

// KnowledgeListResponse 知识库列表响应
type KnowledgeListResponse struct {
	List []KnowledgeBase `json:"data"`
}

// KnowledgeDetailResponse 知识库详情响应
type KnowledgeDetailResponse struct {
	KnowledgeBase KnowledgeBase `json:"data"`
}

// DocumentListResponse 文档列表响应
type DocumentListResponse struct {
	List []KnowledgeDocument `json:"data"`
}

// UploadDocumentResponse 上传文档响应
type UploadDocumentResponse struct {
	Success  bool               `json:"success"`
	ID       string             `json:"id"`
	Document KnowledgeDocument  `json:"document"`
	Message  string             `json:"message"`
}

// DocumentPreviewResponse 文档预览响应
type DocumentPreviewResponse struct {
	TotalPages  int    `json:"total_pages"`
	CurrentPage int    `json:"current_page"`
	Content     string `json:"content"`
	ContentType string `json:"content_type"` // url: 文件URL, html: HTML内容
}
