package at.procon.ted.model.entity;

import at.procon.dip.architecture.SchemaNames;
import jakarta.persistence.*;
import lombok.*;
import org.hibernate.annotations.JdbcTypeCode;
import org.hibernate.type.SqlTypes;

import java.math.BigDecimal;
import java.time.LocalDate;
import java.time.LocalTime;
import java.time.OffsetDateTime;
import java.util.ArrayList;
import java.util.List;
import java.util.UUID;

/**
 * JPA Entity representing an EU eForms procurement document from TED.
 * 
 * Stores the complete XML document along with extracted metadata for efficient querying.
 * Supports semantic search via pgvector embeddings.
 * 
 * @author Martin.Schweitzer@procon.co.at and claude.ai
 */
@Entity
@Table(schema = SchemaNames.TED, name = "procurement_document", indexes = {
    @Index(name = "idx_doc_hash", columnList = "documentHash"),
    @Index(name = "idx_doc_publication_id", columnList = "publicationId"),
    @Index(name = "idx_doc_buyer_country", columnList = "buyerCountryCode"),
    @Index(name = "idx_doc_publication_date", columnList = "publicationDate")
})
@Getter
@Setter
@NoArgsConstructor
@AllArgsConstructor
@Builder
public class ProcurementDocument {

    @Id
    @GeneratedValue(strategy = GenerationType.UUID)
    private UUID id;

    /**
     * SHA-256 hash of the XML content for idempotent processing.
     * Used as the unique key to prevent duplicate document imports.
     */
    @Column(name = "document_hash", nullable = false, unique = true, length = 64)
    private String documentHash;

    // TED/eForms identifiers
    @Column(name = "notice_id", length = 100)
    private String noticeId;

    @Column(name = "publication_id", length = 50)
    private String publicationId;

    /**
     * TED notice URL generated from publication_id.
     * Format: https://ted.europa.eu/en/notice/-/detail/{publication_id without leading zeros}
     * Example: https://ted.europa.eu/en/notice/-/detail/786665-2025
     */
    @Column(name = "notice_url", length = 255)
    private String noticeUrl;

    @Column(name = "ojs_id", length = 20)
    private String ojsId;

    @Column(name = "contract_folder_id", length = 100)
    private String contractFolderId;

    // Document classification
    @Enumerated(EnumType.STRING)
    @Column(name = "notice_type", nullable = false, length = 50)
    @Builder.Default
    private NoticeType noticeType = NoticeType.OTHER;

    @Column(name = "notice_subtype_code", length = 10)
    private String noticeSubtypeCode;

    @Column(name = "sdk_version", length = 20)
    private String sdkVersion;

    @Column(name = "ubl_version", length = 10)
    private String ublVersion;

    @Column(name = "language_code", length = 10)
    private String languageCode;

    // Timestamps
    @Column(name = "issue_datetime")
    private OffsetDateTime issueDateTime;

    @Column(name = "publication_date")
    private LocalDate publicationDate;

    @Column(name = "submission_deadline")
    private OffsetDateTime submissionDeadline;

    // Contracting authority (buyer) information
    @Column(name = "buyer_name", columnDefinition = "TEXT")
    private String buyerName;

    @Column(name = "buyer_country_code", length = 10)
    private String buyerCountryCode;

    @Column(name = "buyer_city", columnDefinition = "TEXT")
    private String buyerCity;

    @Column(name = "buyer_postal_code", columnDefinition = "TEXT")
    private String buyerPostalCode;

    @Column(name = "buyer_nuts_code", length = 10)
    private String buyerNutsCode;

    @Column(name = "buyer_activity_type", length = 50)
    private String buyerActivityType;

    @Column(name = "buyer_legal_type", length = 50)
    private String buyerLegalType;

    // Procurement project details
    @Column(name = "project_title", columnDefinition = "TEXT")
    private String projectTitle;

    @Column(name = "project_description", columnDefinition = "TEXT")
    private String projectDescription;

    @Column(name = "internal_reference", columnDefinition = "TEXT")
    private String internalReference;

    @Enumerated(EnumType.STRING)
    @Column(name = "contract_nature", nullable = false, length = 50)
    @Builder.Default
    private ContractNature contractNature = ContractNature.UNKNOWN;

    @Enumerated(EnumType.STRING)
    @Column(name = "procedure_type", length = 50)
    @Builder.Default
    private ProcedureType procedureType = ProcedureType.OTHER;

    // Classification codes (stored as PostgreSQL arrays)
    @Column(name = "cpv_codes", columnDefinition = "VARCHAR(100)[]")
    @JdbcTypeCode(SqlTypes.ARRAY)
    private String[] cpvCodes;

    @Column(name = "nuts_codes", columnDefinition = "VARCHAR(20)[]")
    @JdbcTypeCode(SqlTypes.ARRAY)
    private String[] nutsCodes;

    // Financial information
    @Column(name = "estimated_value", precision = 20, scale = 2)
    private BigDecimal estimatedValue;

    @Column(name = "estimated_value_currency", length = 3)
    private String estimatedValueCurrency;

    // Lot information
    @Column(name = "total_lots")
    @Builder.Default
    private Integer totalLots = 0;

    @Column(name = "max_lots_awarded")
    private Integer maxLotsAwarded;

    @Column(name = "max_lots_submitted")
    private Integer maxLotsSubmitted;

    // Legal basis
    @Column(name = "regulatory_domain", length = 50)
    private String regulatoryDomain;

    @Column(name = "eu_funded")
    @Builder.Default
    private Boolean euFunded = false;

    /**
     * Normalized text content extracted from the XML for vectorization.
     * Contains title, description, buyer info, and other searchable text.
     */
    @Column(name = "text_content", columnDefinition = "TEXT")
    private String textContent;

    /**
     * Original XML document stored in PostgreSQL native XML type.
     * Enables XPath queries like: xpath('/ContractNotice/cbc:ID/text()', xml_document)
     */
    @Column(name = "xml_document", nullable = false)
    @JdbcTypeCode(SqlTypes.SQLXML)
    private String xmlDocument;

    /**
     * 1024-dimensional vector embedding for semantic search.
     * Generated using intfloat/multilingual-e5-large model.
     *
     * Note: This field is @Transient because the pgvector type is not natively
     * supported by Hibernate/JDBC. Vectors are written via native SQL queries only.
     */
    @Transient
    private float[] contentVector;

    // Vectorization tracking
    @Enumerated(EnumType.STRING)
    @Column(name = "vectorization_status", length = 50)
    @Builder.Default
    private VectorizationStatus vectorizationStatus = VectorizationStatus.PENDING;

    @Column(name = "vectorization_error", columnDefinition = "TEXT")
    private String vectorizationError;

    @Column(name = "vectorized_at")
    private OffsetDateTime vectorizedAt;

    @Column(name = "embedding_token_count")
    private Integer embeddingTokenCount;

    // Processing metadata
    @Column(name = "source_filename", length = 500)
    private String sourceFilename;

    @Column(name = "source_path", columnDefinition = "TEXT")
    private String sourcePath;

    @Column(name = "file_size_bytes")
    private Long fileSizeBytes;

    // Audit fields
    @Column(name = "created_at", nullable = false, updatable = false)
    @Builder.Default
    private OffsetDateTime createdAt = OffsetDateTime.now();

    @Column(name = "updated_at")
    @Builder.Default
    private OffsetDateTime updatedAt = OffsetDateTime.now();

    @Column(name = "processing_duration_ms")
    private Integer processingDurationMs;

    // Relationships
    @OneToMany(mappedBy = "document", cascade = CascadeType.ALL, orphanRemoval = true)
    @Builder.Default
    private List<ProcurementLot> lots = new ArrayList<>();

    @OneToMany(mappedBy = "document", cascade = CascadeType.ALL, orphanRemoval = true)
    @Builder.Default
    private List<Organization> organizations = new ArrayList<>();

    // Helper methods
    public void addLot(ProcurementLot lot) {
        lots.add(lot);
        lot.setDocument(this);
    }

    public void addOrganization(Organization organization) {
        organizations.add(organization);
        organization.setDocument(this);
    }

    @PrePersist
    protected void onCreate() {
        createdAt = OffsetDateTime.now();
        updatedAt = OffsetDateTime.now();
        generateNoticeUrl();
    }

    @PreUpdate
    protected void onUpdate() {
        updatedAt = OffsetDateTime.now();
        generateNoticeUrl();
    }

    /**
     * Generates TED notice URL from publication_id.
     * Format: https://ted.europa.eu/en/notice/-/detail/{publication_id without leading zeros}
     */
    private void generateNoticeUrl() {
        if (publicationId != null && !publicationId.isEmpty()) {
            // Remove leading zeros from publication_id
            String cleanId = publicationId.replaceFirst("^0+", "");
            this.noticeUrl = "https://ted.europa.eu/en/notice/-/detail/" + cleanId;
        }
    }
}
