/**
 * Document Generator types (Legal Templates RAG)
 *
 * License types, template search, document generation,
 * and template ingestion for the legal document generator.
 */

import type { CompanyProfile } from './company-profile'

// =============================================================================
// LICENSE & TEMPLATE ENUMS
// =============================================================================

/**
 * License types for legal templates with compliance metadata
 */
export type LicenseType =
  | 'public_domain'   // SS5 UrhG German official works
  | 'cc0'             // CC0 1.0 Universal
  | 'unlicense'       // Unlicense (public domain)
  | 'mit'             // MIT License
  | 'cc_by_4'         // CC BY 4.0 International
  | 'reuse_notice'    // EU reuse notice (source required)

/**
 * Template types available for document generation
 */
export type TemplateType =
  | 'privacy_policy'
  | 'terms_of_service'
  | 'agb'
  | 'cookie_banner'
  | 'cookie_policy'
  | 'impressum'
  | 'widerruf'
  | 'dpa'
  | 'sla'
  | 'nda'
  | 'cloud_service_agreement'
  | 'data_usage_clause'
  | 'acceptable_use'
  | 'community_guidelines'
  | 'copyright_policy'
  | 'clause'

/**
 * Jurisdiction codes for legal documents
 */
export type Jurisdiction = 'DE' | 'AT' | 'CH' | 'EU' | 'US' | 'INTL'

// =============================================================================
// SEARCH & RESULTS
// =============================================================================

/**
 * A single legal template search result from RAG
 */
export interface LegalTemplateResult {
  id: string
  score: number
  text: string
  documentTitle: string | null
  templateType: TemplateType | null
  clauseCategory: string | null
  language: 'de' | 'en'
  jurisdiction: Jurisdiction | null

  // License information
  licenseId: LicenseType | null
  licenseName: string | null
  licenseUrl: string | null
  attributionRequired: boolean
  attributionText: string | null

  // Source information
  sourceName: string | null
  sourceUrl: string | null
  sourceRepo: string | null
  placeholders: string[]

  // Document characteristics
  isCompleteDocument: boolean
  isModular: boolean
  requiresCustomization: boolean

  // Usage rights
  outputAllowed: boolean
  modificationAllowed: boolean
  distortionProhibited: boolean
}

/**
 * Search request for legal templates
 */
export interface TemplateSearchRequest {
  query: string
  templateType?: TemplateType
  licenseTypes?: LicenseType[]
  language?: 'de' | 'en'
  jurisdiction?: Jurisdiction
  attributionRequired?: boolean
  limit?: number
}

// =============================================================================
// DOCUMENT GENERATION
// =============================================================================

/**
 * Reference to a template used in document generation (for attribution)
 */
export interface TemplateReference {
  templateId: string
  sourceName: string
  sourceUrl: string
  licenseId: LicenseType
  licenseName: string
  attributionRequired: boolean
  attributionText: string | null
  usedAt: string  // ISO timestamp
}

/**
 * A customization applied to a generated document
 */
export interface DocumentCustomization {
  type: 'add_section' | 'modify_section' | 'remove_section' | 'replace_placeholder'
  section: string | null
  originalText: string | null
  newText: string | null
  reason: string | null
  appliedAt: string
}

/**
 * A generated document with attribution tracking
 */
export interface GeneratedDocument {
  id: string
  documentType: TemplateType
  title: string
  content: string
  language: 'de' | 'en'
  jurisdiction: Jurisdiction

  // Templates and sources used
  usedTemplates: TemplateReference[]

  // Generated attribution footer
  attributionFooter: string

  // Customization
  placeholderValues: Record<string, string>
  customizations: DocumentCustomization[]

  // Metadata
  generatedAt: string
  generatedBy: string
  version: number
}

/**
 * Document generation request
 */
export interface DocumentGenerationRequest {
  documentType: TemplateType
  language: 'de' | 'en'
  jurisdiction: Jurisdiction
  templateIds: string[]  // Selected template IDs to use
  placeholderValues: Record<string, string>
  companyProfile?: Partial<CompanyProfile>  // For auto-filling placeholders
  additionalContext?: string
}

// =============================================================================
// DOCUMENT GENERATOR STATE
// =============================================================================

/**
 * State for the document generator feature
 */
export interface DocumentGeneratorState {
  // Search state
  searchQuery: string
  searchResults: LegalTemplateResult[]
  selectedTemplates: string[]  // Template IDs

  // Current document being generated
  currentDocumentType: TemplateType | null
  currentLanguage: 'de' | 'en'
  currentJurisdiction: Jurisdiction

  // Editor state
  editorContent: string
  editorMode: 'preview' | 'edit'
  unsavedChanges: boolean

  // Placeholder values
  placeholderValues: Record<string, string>

  // Generated documents history
  generatedDocuments: GeneratedDocument[]

  // UI state
  isGenerating: boolean
  isSearching: boolean
  lastError: string | null
}

// =============================================================================
// TEMPLATE SOURCES & INGESTION
// =============================================================================

/**
 * Source configuration for legal templates
 */
export interface TemplateSource {
  name: string
  description: string
  licenseType: LicenseType
  licenseName: string
  templateTypes: TemplateType[]
  languages: ('de' | 'en')[]
  jurisdiction: Jurisdiction
  repoUrl: string | null
  webUrl: string | null
  priority: number
  enabled: boolean
  attributionRequired: boolean
}

/**
 * Result of ingesting a single source
 */
export interface SourceIngestionResult {
  status: 'pending' | 'running' | 'completed' | 'failed'
  documentsFound: number
  chunksIndexed: number
  errors: string[]
}

/**
 * Status of template ingestion
 */
export interface TemplateIngestionStatus {
  running: boolean
  lastRun: string | null
  currentSource: string | null
  results: Record<string, SourceIngestionResult>
}

/**
 * Statistics for the legal templates collection
 */
export interface TemplateCollectionStats {
  collection: string
  vectorsCount: number
  pointsCount: number
  status: string
  templateTypes: Record<TemplateType, number>
  languages: Record<string, number>
  licenses: Record<LicenseType, number>
}

// =============================================================================
// DISPLAY LABELS & DEFAULTS
// =============================================================================

/**
 * Default placeholder values commonly used in legal documents
 */
export const DEFAULT_PLACEHOLDERS: Record<string, string> = {
  '[COMPANY_NAME]': '',
  '[FIRMENNAME]': '',
  '[ADDRESS]': '',
  '[ADRESSE]': '',
  '[EMAIL]': '',
  '[PHONE]': '',
  '[TELEFON]': '',
  '[WEBSITE]': '',
  '[LEGAL_REPRESENTATIVE]': '',
  '[GESCHAEFTSFUEHRER]': '',
  '[REGISTER_COURT]': '',
  '[REGISTERGERICHT]': '',
  '[REGISTER_NUMBER]': '',
  '[REGISTERNUMMER]': '',
  '[VAT_ID]': '',
  '[UST_ID]': '',
  '[DPO_NAME]': '',
  '[DSB_NAME]': '',
  '[DPO_EMAIL]': '',
  '[DSB_EMAIL]': '',
}

/**
 * Template type labels for display
 */
export const TEMPLATE_TYPE_LABELS: Record<TemplateType, string> = {
  privacy_policy: 'Datenschutzerkl\u00e4rung',
  terms_of_service: 'Nutzungsbedingungen',
  agb: 'Allgemeine Gesch\u00e4ftsbedingungen',
  cookie_banner: 'Cookie-Banner',
  cookie_policy: 'Cookie-Richtlinie',
  impressum: 'Impressum',
  widerruf: 'Widerrufsbelehrung',
  dpa: 'Auftragsverarbeitungsvertrag',
  sla: 'Service Level Agreement',
  nda: 'Geheimhaltungsvereinbarung',
  cloud_service_agreement: 'Cloud-Dienstleistungsvertrag',
  data_usage_clause: 'Datennutzungsklausel',
  acceptable_use: 'Acceptable Use Policy',
  community_guidelines: 'Community-Richtlinien',
  copyright_policy: 'Urheberrechtsrichtlinie',
  clause: 'Vertragsklausel',
}

/**
 * License type labels for display
 */
export const LICENSE_TYPE_LABELS: Record<LicenseType, string> = {
  public_domain: 'Public Domain (\u00a75 UrhG)',
  cc0: 'CC0 1.0 Universal',
  unlicense: 'Unlicense',
  mit: 'MIT License',
  cc_by_4: 'CC BY 4.0 International',
  reuse_notice: 'EU Reuse Notice',
}

/**
 * Jurisdiction labels for display
 */
export const JURISDICTION_LABELS: Record<Jurisdiction, string> = {
  DE: 'Deutschland',
  AT: '\u00d6sterreich',
  CH: 'Schweiz',
  EU: 'Europ\u00e4ische Union',
  US: 'United States',
  INTL: 'International',
}
