package discovery

import "time"

type ScanStatus string

const (
	ScanPending   ScanStatus = "pending"
	ScanRunning   ScanStatus = "running"
	ScanCompleted ScanStatus = "completed"
	ScanFailed    ScanStatus = "failed"
)

type ProfileStatus string

const (
	ProfileSuggested ProfileStatus = "suggested"
	ProfileAccepted  ProfileStatus = "accepted"
	ProfileRejected  ProfileStatus = "rejected"
	ProfileIgnored   ProfileStatus = "ignored"
	ProfileBlocked   ProfileStatus = "blocked"
)

type EnrichmentStatus string

const (
	EnrichPending   EnrichmentStatus = "pending"
	EnrichEnriching EnrichmentStatus = "enriching"
	EnrichEnriched  EnrichmentStatus = "enriched"
	EnrichSkipped   EnrichmentStatus = "skipped"
	EnrichFailed    EnrichmentStatus = "failed"
)

type SuggestionStatus string

const (
	SuggestionPending  SuggestionStatus = "pending"
	SuggestionAccepted SuggestionStatus = "accepted"
	SuggestionRejected SuggestionStatus = "rejected"
)

type ScanPhase string

const (
	PhasePending    ScanPhase = "pending"
	PhaseScanning   ScanPhase = "scanning_messages"
	PhaseProfiles   ScanPhase = "building_profiles"
	PhaseEnriching  ScanPhase = "enriching"
	PhaseDone       ScanPhase = "done"
)

type Scan struct {
	ID              string     `json:"id"`
	Status          ScanStatus `json:"status"`
	Phase           ScanPhase  `json:"phase"`
	MessagesScanned int        `json:"messages_scanned"`
	TotalMessages   int        `json:"total_messages"`
	ProfilesFound   int        `json:"profiles_found"`
	ProfilesTotal   int        `json:"profiles_total"`
	ProgressPercent float64    `json:"progress_percent"`
	ErrorMessage    string     `json:"error_message,omitempty"`
	StartedAt       time.Time  `json:"started_at"`
	UpdatedAt       time.Time  `json:"updated_at"`
	CompletedAt     *time.Time `json:"completed_at,omitempty"`
}

type AccountDetection struct {
	AccountID     string `json:"account_id"`
	AccountEmail  string `json:"account_email"`
	AccountName   string `json:"account_name"`
	MessageCount  int    `json:"message_count"`
}

type EmailEntry struct {
	Email        string `json:"email"`
	DisplayName  string `json:"display_name"`
	Roles        []string `json:"roles,omitempty"`
	MessageCount int    `json:"message_count"`
}

type SignatureEntry struct {
	ID            string    `json:"id"`
	MessageID     string    `json:"message_id,omitempty"`
	SignatureText string    `json:"signature_text"`
	MessageDate   time.Time `json:"message_date"`
	Confidence    float64   `json:"confidence"`
}

type EnrichedContactData struct {
	FirstName   string            `json:"first_name,omitempty"`
	LastName    string            `json:"last_name,omitempty"`
	Company     string            `json:"company,omitempty"`
	Department  string            `json:"department,omitempty"`
	JobTitle    string            `json:"job_title,omitempty"`
	Emails      []FieldWithLabel  `json:"emails,omitempty"`
	Phones      []FieldWithLabel  `json:"phones,omitempty"`
	Addresses      []AddressField   `json:"addresses,omitempty"`
	Website        string           `json:"website,omitempty"`
	SocialProfiles []FieldWithLabel `json:"social_profiles,omitempty"`
	Notes          string           `json:"notes,omitempty"`
}

type FieldWithLabel struct {
	Value string `json:"value"`
	Label string `json:"label"`
}

type AddressField struct {
	Street     string `json:"street,omitempty"`
	City       string `json:"city,omitempty"`
	Region     string `json:"region,omitempty"`
	PostalCode string `json:"postal_code,omitempty"`
	Country    string `json:"country,omitempty"`
	Label      string `json:"label"`
}

type ProfileGroup struct {
	GroupKey     string    `json:"group_key"`
	ProfileIDs   []string  `json:"profile_ids"`
	DisplayName  string    `json:"display_name"`
	PrimaryEmail string    `json:"primary_email"`
	MessageCount int       `json:"message_count"`
	Profile      Profile   `json:"profile"`
	Profiles     []Profile `json:"profiles"`
}

type Profile struct {
	ID                   string               `json:"id"`
	DisplayName          string               `json:"display_name"`
	PrimaryEmail         string               `json:"primary_email"`
	AllEmails            []EmailEntry         `json:"all_emails"`
	MessageCount         int                  `json:"message_count"`
	SentCount            int                  `json:"sent_count"`
	ReceivedCount        int                  `json:"received_count"`
	OutboundCount        int                  `json:"outbound_count"`
	InboundFromCCCount   int                  `json:"inbound_from_cc_count"`
	CopresenceCCBCCCount int                  `json:"copresence_cc_bcc_count"`
	SpamCount            int                  `json:"spam_count"`
	ForwardedCount       int                  `json:"forwarded_count"`
	IsMailingList        bool                 `json:"is_mailing_list"`
	IsDisposable         bool                 `json:"is_disposable"`
	IsSpamHeavy          bool                 `json:"is_spam_heavy"`
	ClassificationReason string               `json:"classification_reason,omitempty"`
	LinkedContactUID     string               `json:"linked_contact_uid,omitempty"`
	EnrichmentStatus     EnrichmentStatus     `json:"enrichment_status"`
	EnrichedData         *EnrichedContactData `json:"enriched_data,omitempty"`
	Status               ProfileStatus        `json:"status"`
	Signatures           []SignatureEntry     `json:"signatures,omitempty"`
	DetectedInAccounts   []AccountDetection   `json:"detected_in_accounts,omitempty"`
	LastMessageAt        *time.Time           `json:"last_message_at,omitempty"`
}

type Suggestion struct {
	ID               string           `json:"id"`
	ProfileID        string           `json:"profile_id,omitempty"`
	TargetContactUID string           `json:"target_contact_uid,omitempty"`
	SuggestionType   string           `json:"suggestion_type"`
	FieldPath        string           `json:"field_path"`
	SuggestedValue   string           `json:"suggested_value"`
	SuggestedLabel   string           `json:"suggested_label"`
	Confidence       float64          `json:"confidence"`
	Status           SuggestionStatus `json:"status"`
	Profile          *Profile         `json:"profile,omitempty"`
}

type ScanResult struct {
	Scan     Scan      `json:"scan"`
	Profiles []Profile `json:"profiles,omitempty"`
}

type fromMessageRef struct {
	id   string
	date time.Time
}

type addressAgg struct {
	Email        string
	DisplayName  string
	Roles        map[string]struct{}
	MessageCount int
	SentCount           int
	ReceivedCount       int
	OutboundCount       int
	InboundFromCCCount  int
	CopresenceCCBCCCount int
	SpamCount           int
	ForwardedCount int
	LastSeen     time.Time
	Signatures   []signatureCandidate
	fromMessageRefs []fromMessageRef
	ListUnsub    int
	MailingList  int
	Accounts     map[string]*AccountDetection
}

type signatureCandidate struct {
	MessageID     string
	SignatureText string
	SignatureHTML string
	MessageDate   time.Time
	Confidence    float64
}

type messageRow struct {
	ID           string
	Subject      string
	FromAddr     []byte
	ToAddrs      []byte
	CcAddrs      []byte
	BccAddrs     []byte
	ReplyTo       []byte
	Snippet       string
	BodyText      string
	BodyHTML      string
	Date         time.Time
	Flags        []string
	Labels       []string
	AuthInfo     []byte
	FolderType    string
	AccountID     string
	AccountEmail  string
	AccountName   string
}
