// Package atomize is the app-side client of the Atomization Service (§5.1)
// plus the coefficient validation/normalization rules.
package atomize

import (
	"context"
	"errors"
	"fmt"
	"math"
	"net/http"
	"time"

	"bountyboard/internal/extsvc"
)

type Attachment struct {
	Name     string `json:"name"`
	URL      string `json:"url"`
	MimeType string `json:"mimeType"`
}

type Constraints struct {
	MinTasks int `json:"minTasks,omitempty"`
	MaxTasks int `json:"maxTasks,omitempty"`
}

type AtomizeRequest struct {
	TaskID             string       `json:"taskId"`
	Title              string       `json:"title"`
	Description        string       `json:"description"`
	AcceptanceCriteria []string     `json:"acceptanceCriteria"`
	Attachments        []Attachment `json:"attachments"`
	Links              []string     `json:"links"`
	SubdivisionNote    string       `json:"subdivisionNote,omitempty"`
	Constraints        *Constraints `json:"constraints,omitempty"`
}

type ExtendRequest struct {
	TaskID             string       `json:"taskId"`
	Title              string       `json:"title"`
	Description        string       `json:"description"`
	AcceptanceCriteria []string     `json:"acceptanceCriteria"`
	Attachments        []Attachment `json:"attachments"`
	Links              []string     `json:"links"`
	ExtensionNote      string       `json:"extensionNote"`
}

type SubTask struct {
	Title              string   `json:"title"`
	Description        string   `json:"description"`
	AcceptanceCriteria []string `json:"acceptanceCriteria"`
	EffortCoefficient  float64  `json:"effortCoefficient"`
}

type AtomizeResponse struct {
	Tasks []SubTask `json:"tasks"`
	Model string    `json:"model,omitempty"`
	Notes string    `json:"notes,omitempty"`
}

type ExtendResponse struct {
	Task  SubTask `json:"task"`
	Model string  `json:"model,omitempty"`
	Notes string  `json:"notes,omitempty"`
}

// ErrBadCoefficients is the 502-class rejection when the service returns
// coefficients we are not willing to repair (§5.1).
var ErrBadCoefficients = errors.New("atomizer returned invalid effort coefficients")

type Client struct {
	c *extsvc.Client
}

// New builds the client. baseURL is resolved per call so the admin settings
// override applies without restart.
func New(baseURL func() string, token string, timeout time.Duration) *Client {
	return &Client{c: extsvc.NewClient("atomizer", baseURL, token, timeout)}
}

func (a *Client) BreakerState() string              { return a.c.BreakerState() }
func (a *Client) Healthy(ctx context.Context) error { return a.c.Healthy(ctx) }

// Atomize calls POST /v1/atomize and applies the §5.1 contract: coefficients
// must sum to 1 ± 0.001; a deviation ≤ 0.05 is defensively renormalized,
// anything worse is rejected as a service error.
func (a *Client) Atomize(ctx context.Context, req AtomizeRequest) (*AtomizeResponse, error) {
	var resp AtomizeResponse
	if err := a.c.Call(ctx, http.MethodPost, "/v1/atomize", req, &resp); err != nil {
		return nil, err
	}
	if len(resp.Tasks) == 0 {
		return nil, fmt.Errorf("%w: empty task list", ErrBadCoefficients)
	}
	coeffs := make([]float64, len(resp.Tasks))
	for i, t := range resp.Tasks {
		coeffs[i] = t.EffortCoefficient
	}
	normalized, err := NormalizeCoefficients(coeffs)
	if err != nil {
		return nil, err
	}
	for i := range resp.Tasks {
		resp.Tasks[i].EffortCoefficient = normalized[i]
	}
	return &resp, nil
}

// Extend calls POST /v1/extend. The sibling coefficient is relative to the
// source task and may exceed 1 up to 2.0 (§5.1).
func (a *Client) Extend(ctx context.Context, req ExtendRequest) (*ExtendResponse, error) {
	var resp ExtendResponse
	if err := a.c.Call(ctx, http.MethodPost, "/v1/extend", req, &resp); err != nil {
		return nil, err
	}
	c := resp.Task.EffortCoefficient
	if c <= 0 || c > 2.0 || math.IsNaN(c) {
		return nil, fmt.Errorf("%w: extension coefficient %v outside (0, 2]", ErrBadCoefficients, c)
	}
	return &resp, nil
}

// NormalizeCoefficients enforces the §5.1 sum contract. Each coefficient
// must be in (0, 1]; the sum must be 1 ± 0.001 (accepted as-is) or within
// ± 0.05 (renormalized proportionally, then rounded to 4 decimals with the
// remainder folded into the largest entry so the sum is exactly 1).
func NormalizeCoefficients(coeffs []float64) ([]float64, error) {
	if len(coeffs) == 0 {
		return nil, fmt.Errorf("%w: empty", ErrBadCoefficients)
	}
	sum := 0.0
	for _, c := range coeffs {
		if math.IsNaN(c) || c <= 0 || c > 1 {
			return nil, fmt.Errorf("%w: coefficient %v outside (0, 1]", ErrBadCoefficients, c)
		}
		sum += c
	}
	if math.Abs(sum-1) > 0.05 {
		return nil, fmt.Errorf("%w: sum %.4f deviates more than 0.05 from 1", ErrBadCoefficients, sum)
	}
	out := make([]float64, len(coeffs))
	largest := 0
	total := 0.0
	for i, c := range coeffs {
		out[i] = math.Round(c/sum*10000) / 10000
		total += out[i]
		if out[i] > out[largest] {
			largest = i
		}
	}
	out[largest] = math.Round((out[largest]+1-total)*10000) / 10000
	return out, nil
}
