import axios from 'axios'
import request from '@/utils/http'
import { useUserStore } from '@/store/modules/user'

export interface Application { id:string;code:string;name:string;description:string;published_version?:number }
export interface Knowledge { id:string;name:string;description:string;document_count:number;chunk_count:number }
export interface Tool { id:string;code:string;name:string;description:string;input_schema:Record<string,unknown> }
export interface PromptVersion { version:number;content:string;variables:Array<{name:string;label?:string;required:boolean}> }
export interface Prompt { id:string;name:string;description:string;category_name:string;tags:string[];favorite:boolean;current?:PromptVersion }
export interface Catalog { applications:Application[];knowledge:Knowledge[];tools:Tool[];prompts:Prompt[] }
export interface Model { provider_code:string;id:string;owned_by:string }
export interface ModelRequest { id:string;provider_code:string;model:string;reason:string;requested_rpm:number;requested_monthly_tokens:number;status:string;decision_note:string;created_at:string }
export interface Stats { days:number;requests:number;failed_requests:number;prompt_tokens:number;completion_tokens:number;total_tokens:number;cost_microunits:number;avg_latency_ms?:number }
export interface AuditEvent { id:string;request_id:string;provider_code?:string;model?:string;protocol:string;status_code?:number;prompt_tokens?:number;completion_tokens?:number;cost_microunits?:number;latency_ms?:number;recorded_at:string }

export const fetchCatalog=()=>request.get<Catalog>({url:'/api/v1/portal/catalog'})
export const fetchPrompts=(q='')=>request.get<Prompt[]>({url:'/api/v1/portal/prompts',params:{q}})
export const setPromptFavorite=(id:string,value:boolean)=>value?request.post({url:`/api/v1/portal/prompts/${id}/favorite`}):request.del({url:`/api/v1/portal/prompts/${id}/favorite`})
export const fetchModels=()=>request.get<Model[]>({url:'/api/v1/portal/model-requests/available'})
export const fetchModelRequests=()=>request.get<ModelRequest[]>({url:'/api/v1/portal/model-requests'})
export const createModelRequest=(params:Pick<ModelRequest,'provider_code'|'model'|'reason'|'requested_rpm'|'requested_monthly_tokens'>)=>request.post<ModelRequest>({url:'/api/v1/portal/model-requests',params})
export const fetchStats=(days:number)=>request.get<Stats>({url:'/api/v1/portal/stats',params:{days}})
export const fetchLogs=(days:number,limit=50)=>request.get<{items:AuditEvent[]}>({url:'/api/v1/portal/logs',params:{days,limit}})
export const changePassword=(params:{old_password:string;new_password:string})=>request.post({url:'/api/v1/portal/password',params})

// --- 站内消息（M8 P4）---
export interface InboxMessage { id:string;recipient_kind:string;recipient_user_id:string;sender_type:string;category:string;title:string;body:string;link:string;payload?:Record<string,unknown>;read_at?:string;created_at:string }
export const fetchInbox=()=>request.get<InboxMessage[]>({url:'/api/v1/portal/inbox'})
export const fetchInboxUnread=()=>request.get<{unread:number}>({url:'/api/v1/portal/inbox/unread'})
export const markInboxRead=(id:string)=>request.post<{read:boolean}>({url:`/api/v1/portal/inbox/${id}/read`})
export const markInboxAllRead=()=>request.post<{read_all:number}>({url:'/api/v1/portal/inbox/read-all'})

// --- 个人文件仓库（M8 对象存储）---
export interface FileObject { id:string;original_name:string;content_type:string;size_bytes:number;content_sha256:string;scope:string;created_at:string;updated_at:string }
export const fetchMyFiles=()=>request.get<FileObject[]>({url:'/api/v1/portal/files'})
export const uploadMyFile=(file:File)=>{
  const form=new FormData()
  form.append('file',file)
  return request.post<FileObject>({url:'/api/v1/portal/files',data:form,timeout:120000})
}
export const deleteMyFile=(id:string)=>request.del({url:`/api/v1/portal/files/${id}`})
export async function downloadMyFile(id:string,filename:string){
  const { accessToken } = useUserStore()
  const token = accessToken.startsWith('Bearer ')?accessToken:`Bearer ${accessToken}`
  const res = await axios.get(`/api/v1/portal/files/${id}/download`,{
    baseURL:import.meta.env.VITE_API_URL,
    headers:{Authorization:token},
    responseType:'blob'
  })
  const url = URL.createObjectURL(res.data)
  const anchor = document.createElement('a')
  anchor.href = url
  anchor.download = filename
  anchor.click()
  URL.revokeObjectURL(url)
}


// --- 资源市场 ---
export interface MarketItem { type:string;code:string;name:string;description:string;category_id?:string;category_name:string;tags:string[];department_ids:string[];updated_at:string }
export interface MarketplaceCategory { id:string;name:string;description:string;resource_type:string;sort_order:number }
export const fetchMarketplace=(params?:{type?:string;category_id?:string;tag?:string;q?:string})=>request.get<MarketItem[]>({url:'/api/v1/portal/marketplace',params})
export const fetchMarketplaceCategories=()=>request.get<MarketplaceCategory[]>({url:'/api/v1/portal/marketplace/categories'})
export const fetchMarketplaceInstalled=()=>request.get<MarketItem[]>({url:'/api/v1/portal/marketplace/installed'})
export const fetchMarketplaceDetail=(type:string,code:string)=>request.get<{item:MarketItem;detail:Record<string,unknown>}>({url:`/api/v1/portal/marketplace/${type}/${code}`})
export const marketplaceInstall=(type:string,code:string)=>request.post<{installed:boolean;created:boolean}>({url:`/api/v1/portal/marketplace/${type}/${code}/install`})
export const marketplaceUninstall=(type:string,code:string)=>request.del<{installed:boolean}>({url:`/api/v1/portal/marketplace/${type}/${code}/install`})

// --- 通用聊天 ---
export interface ChatModel { provider_code:string;model:string;approved_at:string }
export interface ChatMessage { sequence:number;role:'user'|'assistant';content:string;created_at:string }
export interface ChatSession { id:string;title:string;provider_code:string;model:string;status:string;messages?:ChatMessage[];created_at:string;updated_at:string }
export const fetchChatModels=()=>request.get<ChatModel[]>({url:'/api/v1/portal/chat/models'})
export const chatOnce=(params:{provider_code:string;model:string;message:string})=>request.post<Record<string,unknown>>({url:'/api/v1/portal/chat/completions',params})
export const fetchChatSessions=()=>request.get<ChatSession[]>({url:'/api/v1/portal/chat/sessions'})
export const createChatSession=(params:{provider_code:string;model:string})=>request.post<ChatSession>({url:'/api/v1/portal/chat/sessions',params})
export const renameChatSession=(id:string,title:string)=>request.put<ChatSession>({url:`/api/v1/portal/chat/sessions/${id}`,params:{title}})
export const deleteChatSession=(id:string)=>request.del({url:`/api/v1/portal/chat/sessions/${id}`})
export const fetchChatSession=(id:string)=>request.get<ChatSession>({url:`/api/v1/portal/chat/sessions/${id}`})
export const appendChatMessage=(id:string,message:string)=>request.post<Record<string,unknown>>({url:`/api/v1/portal/chat/sessions/${id}/messages`,params:{message}})

// --- 账号安全 ---
export interface SessionView { id:string;ip:string;user_agent:string;issued_at:number;current:boolean }
export interface ProviderBinding { kind:'wecom'|'dingtalk'|'feishu';provider_uid:string;created_at:string }
export const fetchMySessions=()=>request.get<SessionView[]>({url:'/api/v1/portal/sessions'})
export const revokeSession=(id:string)=>request.post({url:`/api/v1/portal/sessions/${id}/revoke`})
export const fetchSecurityPrefs=()=>request.get<{login_notify:boolean}>({url:'/api/v1/portal/security/prefs'})
export const setSecurityPrefs=(login_notify:boolean)=>request.put<{login_notify:boolean}>({url:'/api/v1/portal/security/prefs',params:{login_notify}})
export const fetchProviderBindings=()=>request.get<ProviderBinding[]>({url:'/api/v1/portal/social/bindings'})
export const startSocialBind=(kind:string)=>request.post<{redirect_url:string}>({url:`/api/v1/portal/social/${kind}/bind/start`})
export const unbindSocial=(kind:string)=>request.del({url:`/api/v1/portal/social/${kind}/bind`})

// --- 资源/渠道权限申请 ---
export interface ResourceRequest { id:string;user_login:string;resource_type:string;resource_code:string;reason:string;status:string;decision_note:string;created_at:string;updated_at:string }
export const fetchMyResourceRequests=()=>request.get<ResourceRequest[]>({url:'/api/v1/portal/resource-requests'})
export const createResourceRequest=(params:{resource_type:string;resource_code:string;reason:string})=>request.post<ResourceRequest>({url:'/api/v1/portal/resource-requests',params})
export const cancelResourceRequest=(id:string)=>request.del({url:`/api/v1/portal/resource-requests/${id}`})

// --- 个人渠道 ---
export interface PersonalChannel { id:string;code:string;name:string;kind:string;provider_code:string;model:string;enabled:boolean;last_used_at?:string;created_at:string;updated_at:string }
export const fetchPersonalChannels=()=>request.get<PersonalChannel[]>({url:'/api/v1/portal/personal-channels'})
export const createPersonalChannel=(params:{code:string;name:string;provider_code:string;model:string})=>request.post<{channel:PersonalChannel;inbound_token:string;inbound_url:string}>({url:'/api/v1/portal/personal-channels',params})
export const regeneratePersonalToken=(id:string)=>request.post<{inbound_token:string}>({url:`/api/v1/portal/personal-channels/${id}/token`})
export const deletePersonalChannel=(id:string)=>request.del({url:`/api/v1/portal/personal-channels/${id}`})

// --- 数字员工 ---
export interface DigitalEmployee { code:string;name:string;description:string;installed:boolean }
export interface EmployeeRun { employee_code:string;employee_name:string;status:string;latency_ms:number;retrieval_count:number;tool_count:number;error:string;created_at:string }
export const fetchDigitalEmployees=()=>request.get<DigitalEmployee[]>({url:'/api/v1/portal/digital-employees'})
export const runDigitalEmployee=(code:string,message:string)=>request.post<Record<string,unknown>>({url:`/api/v1/portal/digital-employees/${code}/chat`,params:{message}})
export const fetchMyEmployeeRuns=(limit=20)=>request.get<EmployeeRun[]>({url:'/api/v1/portal/digital-employees/runs',params:{limit}})

// --- 个人智能体安全策略 ---
export interface AgentPolicy { auto_approve_tools:boolean;rate_limit_multiplier:number }
export const fetchAgentPolicy=()=>request.get<AgentPolicy>({url:'/api/v1/portal/agent-policy'})
export const setAgentPolicy=(params:AgentPolicy)=>request.put<{saved:boolean}>({url:'/api/v1/portal/agent-policy',params})

// --- 我的渠道(部门可见或已授权) ---
export interface VisibleChannel { id:string;code:string;name:string;kind:string;model_binding?:Record<string,unknown>;department_ids:string[];enabled:boolean }
export const fetchMyChannels=()=>request.get<{channels:VisibleChannel[];granted_codes:string[]}>({url:'/api/v1/portal/channels'})
