git/intake/main
internal/plan/plan.go
831 lines26 KB last change raw · history
  1
  2
  3
  4
  5
  6
  7
  8
  9
 10
 11
 12
 13
 14
 15
 16
 17
 18
 19
 20
 21
 22
 23
 24
 25
 26
 27
 28
 29
 30
 31
 32
 33
 34
 35
 36
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
package plan

import (
	"errors"
	"fmt"
	"path/filepath"
	"sort"
	"strings"

	"intake/internal/normalize"
	"intake/internal/scan"
	"intake/internal/sheet"
	"intake/internal/tags"
)

type Issue struct {
	Hard bool
	Text string
}

type TrackPlan struct {
	Source    string
	Title     string
	Artist    string
	Disc      int
	Number    int
	Target    string
	Ext       string
	Duration  float64
	Original  string
	Truncated bool
	Tags      []tags.Note
}

type Plan struct {
	Album          scan.Album
	AlbumName      string
	AlbumTag       string
	AlbumArt       string
	CreditFromTags string
	Artist         string
	Year           string
	VariousArt     bool
	AlbumDir       string
	ArtistDir      string
	ArchiveDir     string
	LibraryDir     string
	ArchiveRoot    string
	LibraryRoot    string
	// DiscPrefix and Width are the naming shape the plan was built with. An
	// edit has to keep it: recomputing the padding from the tracks that are left
	// would silently rename every file in an album whose highest-numbered track
	// was just deleted.
	DiscPrefix string
	Width      int
	Tracks     []TrackPlan
	Issues     []Issue
	Dropped    []string
	Warnings   []string
}

func (p Plan) Blocked() bool {
	for _, i := range p.Issues {
		if i.Hard {
			return true
		}
	}
	return false
}

const (
	variousArtists = "Various Artists"
	specialVA      = "various-artists"
)

type resolved struct {
	title  string
	disc   int
	track  int
	artist string
	src    string
	orig   string
	dur    float64
}

type DirKey struct {
	Dir    string
	Credit string
	Source string
}

// maxNameBytes is the longest name intake writes for a file or a directory.
// Filesystems cap a single path component at 255 bytes, and the archive is built
// inside a temporary directory whose name is the target's with a prefix and a
// random suffix, so the target has to leave room for that.
const maxNameBytes = 200

func Build(a scan.Album, archiveRoot, libraryRoot string, artistKey DirKey, discPrefix string) Plan {
	p := Plan{Album: a, ArchiveRoot: archiveRoot, LibraryRoot: libraryRoot}
	if len(a.Tracks) == 0 {
		p.Issues = append(p.Issues, Issue{Hard: true, Text: "no readable audio tracks"})
		return p
	}

	albumName, albumNameOK := commonValue(a, tags.FieldAlbum)
	albumArtist, albumArtistOK := commonValue(a, tags.FieldAlbumArtist)
	artist, artistOK := commonValue(a, tags.FieldArtist)
	yearRaw, _ := commonValue(a, tags.FieldDate)

	// Tracks that disagree on an album-level value are treated as not having
	// agreed at all, but one mistagged track out of fifteen should not stop the
	// album: a clear majority is used, and said out loud.
	if !albumNameOK {
		if v, n, total := dominantValue(a, tags.FieldAlbum); n*2 > total {
			albumName, albumNameOK = v, true
			p.Warnings = append(p.Warnings, fmt.Sprintf("tracks disagree on ALBUM; %d of %d say %q, using that", n, total, v))
		}
	}
	if !albumArtistOK {
		if v, n, total := dominantValue(a, tags.FieldAlbumArtist); n*2 > total {
			albumArtist, albumArtistOK = v, true
			p.Warnings = append(p.Warnings, fmt.Sprintf("tracks disagree on ALBUMARTIST; %d of %d say %q, using that", n, total, v))
		}
	}

	if !albumArtistOK {
		switch {
		case artistOK:
			albumArtist = artist
			p.Warnings = append(p.Warnings, fmt.Sprintf("no ALBUMARTIST tag; using ARTIST %q", artist))
		default:
			if dominant, n, total := dominantArtist(a); n*2 > total {
				albumArtist = dominant
				p.Warnings = append(p.Warnings, fmt.Sprintf("no ALBUMARTIST tag and the artists differ; %d of %d tracks credit %q, using that", n, total, dominant))
			} else if inferred, _, ok := splitDirName(a.Name); ok {
				albumArtist = inferred
				p.Warnings = append(p.Warnings, fmt.Sprintf("no artist tags at all; inferred artist %q from the directory name", inferred))
			}
		}
	}
	if !albumNameOK {
		if _, inferred, ok := splitDirName(a.Name); ok {
			albumName = inferred
			p.Warnings = append(p.Warnings, fmt.Sprintf("no ALBUM tag; inferred %q from the directory name", inferred))
		}
	}

	// Only when nothing above found an album artist does differing per-track
	// artists mean a compilation. An album with guest tracks still has one album
	// artist, and that is what ALBUMARTIST is for.
	if strings.TrimSpace(albumArtist) == "" && differingArtists(a) {
		p.VariousArt = true
		albumArtist = variousArtists
		p.Warnings = append(p.Warnings, "per-track artists differ and there is no album artist; filing under various-artists")
	}

	if strings.TrimSpace(albumArtist) == "" {
		p.Issues = append(p.Issues, Issue{Hard: true, Text: "album artist is unknown: no ALBUMARTIST/ARTIST tag and the directory name gives no hint"})
	}
	if strings.TrimSpace(albumName) == "" {
		p.Issues = append(p.Issues, Issue{Hard: true, Text: "album name is unknown: no ALBUM tag and the directory name gives no hint"})
	}

	// The archive holds lossless masters: every file intake writes is FLAC, and
	// the tagging and artwork tools it drives are FLAC tools. A lossy source is a
	// design decision rather than a half-working fallback, so it is refused here
	// with something the user can act on, instead of failing much later inside
	// metaflac with "does not appear to be a FLAC file".
	notFLAC := map[string]bool{}
	for _, t := range a.Tracks {
		if ext := strings.ToLower(filepath.Ext(t.Path)); ext != ".flac" {
			notFLAC[strings.TrimPrefix(ext, ".")] = true
		}
	}
	if len(notFLAC) > 0 {
		kinds := make([]string, 0, len(notFLAC))
		for k := range notFLAC {
			kinds = append(kinds, k)
		}
		sort.Strings(kinds)
		p.Issues = append(p.Issues, Issue{Hard: true, Text: fmt.Sprintf("the archive holds flac only, and this album contains %s; convert it to flac first, or file it by hand", strings.Join(kinds, ", "))})
	}

	// One audio file beside a cue sheet is usually a whole album the cue
	// describes as many tracks. intake does not split on cue sheets, so filing it
	// silently would leave the user with an album whose track list is wrong.
	if len(a.Tracks) == 1 && a.Dir != "" {
		if cues, _ := filepath.Glob(filepath.Join(a.Dir, "*.cue")); len(cues) > 0 {
			p.Warnings = append(p.Warnings, fmt.Sprintf("a cue sheet is present (%s) and there is only one audio file; intake does not split on cue sheets, so this will be filed as a single track", filepath.Base(cues[0])))
		}
	}

	p.AlbumName = albumName
	p.AlbumTag = albumName
	p.AlbumArt = albumArtist
	p.CreditFromTags = albumArtist
	p.Year = tags.NormalizeYear(yearRaw)
	if yearRaw != "" && p.Year == "" {
		p.Warnings = append(p.Warnings, fmt.Sprintf("could not read a year from DATE=%q", yearRaw))
	}

	dropped := map[string]bool{}
	for _, t := range a.Tracks {
		for _, d := range tags.Dropped(t.Tags) {
			dropped[d] = true
		}
	}
	for d := range dropped {
		p.Dropped = append(p.Dropped, d)
	}
	sort.Strings(p.Dropped)

	var items []resolved
	maxTrack := 0
	missingNumbers := 0
	for _, t := range a.Tracks {
		base := filepath.Base(t.Path)
		fDisc, fTrack, fTitle := scan.FromFilename(base)

		title, ok := tags.Get(t.Tags, tags.FieldTitle)
		if !ok || strings.TrimSpace(title) == "" {
			title = fTitle
			if title != "" {
				p.Warnings = append(p.Warnings, fmt.Sprintf("%s: no TITLE tag; using the file name %q", base, title))
			}
		}
		original := title

		num := 0
		if v, ok := tags.Get(t.Tags, tags.FieldTrackNumber); ok {
			fmt.Sscanf(strings.TrimSpace(v), "%d", &num)
		}
		if num == 0 && fTrack > 0 {
			num = fTrack
			p.Warnings = append(p.Warnings, fmt.Sprintf("%s: no TRACKNUMBER tag; inferring track %d from the file name", base, num))
		}
		if num == 0 {
			missingNumbers++
		}

		disc := 0
		if v, ok := tags.Get(t.Tags, tags.FieldDiscNumber); ok {
			fmt.Sscanf(strings.TrimSpace(v), "%d", &disc)
		}
		if disc == 0 && fDisc > 0 {
			disc = fDisc
		}
		if disc == 0 && t.DiscHint > 0 {
			// Last resort, and only when the tags and the file name both said
			// nothing: the folder the file sits in, for rips arranged as CD1,
			// CD2 with no disc tags at all.
			disc = t.DiscHint
		}
		if disc == 0 {
			disc = 1
		}

		trArtist, _ := tags.Get(t.Tags, tags.FieldArtist)
		if strings.TrimSpace(trArtist) == "" {
			trArtist = albumArtist
		}
		if num > maxTrack {
			maxTrack = num
		}
		if strings.TrimSpace(title) == "" {
			p.Issues = append(p.Issues, Issue{Hard: true, Text: fmt.Sprintf("%s: no usable title (tag and file name are empty)", base)})
		}
		items = append(items, resolved{title: title, disc: disc, track: num, artist: trArtist, src: t.Path, orig: original, dur: t.Duration})
	}

	if missingNumbers > 0 {
		p.Warnings = append(p.Warnings, fmt.Sprintf("%d track(s) have no track number; they will be numbered in file order", missingNumbers))
		used := map[int]bool{}
		for _, it := range items {
			if it.track > 0 {
				used[it.track] = true
			}
		}
		next := 1
		for i := range items {
			if items[i].track != 0 {
				continue
			}
			for used[next] {
				next++
			}
			items[i].track = next
			used[next] = true
			next++
		}
		for _, it := range items {
			if it.track > maxTrack {
				maxTrack = it.track
			}
		}
	}

	width := normalize.PadWidth(maxTrack)
	p.Width = width
	p.DiscPrefix = discPrefix

	tracksOnDisc := map[int]int{}
	for _, it := range items {
		tracksOnDisc[it.disc]++
	}
	discTotal := len(tracksOnDisc)
	withDisc := useDiscPrefix(discPrefix, discTotal)
	if !withDisc && discTotal > 1 {
		p.Warnings = append(p.Warnings, fmt.Sprintf("disc_prefix is %q but this album has %d discs, so tracks on different discs will share numbers", discPrefix, discTotal))
	}

	var pairs, bySource [][2]string
	for _, it := range items {
		target := normalize.TrackFile(it.disc, it.track, width, it.title, filepath.Ext(it.src), withDisc)
		pairs = append(pairs, [2]string{it.orig, target})
		bySource = append(bySource, [2]string{filepath.Base(it.src), target})
	}
	noteCollisions(&p, pairs, bySource)

	for _, it := range items {
		name := normalize.TrackFile(it.disc, it.track, width, it.title, filepath.Ext(it.src), withDisc)
		truncated := false
		if n, cut := normalize.Truncate(name, maxNameBytes); cut {
			p.Warnings = append(p.Warnings, fmt.Sprintf("target name was too long and has been shortened: %s -> %s", name, n))
			name, truncated = n, true
		}
		tp := TrackPlan{
			Source:    it.src,
			Title:     it.title,
			Artist:    it.artist,
			Disc:      it.disc,
			Number:    it.track,
			Target:    name,
			Ext:       filepath.Ext(it.src),
			Duration:  it.dur,
			Original:  it.orig,
			Truncated: truncated,
		}
		trackTotal := tracksOnDisc[it.disc]
		tp.Tags = []tags.Note{
			{Field: tags.FieldTrackNumber, Value: fmt.Sprintf("%d", it.track)},
			{Field: tags.FieldTrackTotal, Value: fmt.Sprintf("%d", trackTotal)},
			{Field: tags.FieldLegacyTrackTotal, Value: fmt.Sprintf("%d", trackTotal)},
			{Field: tags.FieldDiscNumber, Value: fmt.Sprintf("%d", it.disc)},
			{Field: tags.FieldDiscTotal, Value: fmt.Sprintf("%d", discTotal)},
			{Field: tags.FieldLegacyDiscTotal, Value: fmt.Sprintf("%d", discTotal)},
			{Field: tags.FieldTitle, Value: strings.TrimSpace(it.title)},
			{Field: tags.FieldAlbum, Value: strings.TrimSpace(albumName)},
			{Field: tags.FieldArtist, Value: strings.TrimSpace(it.artist)},
			{Field: tags.FieldAlbumArtist, Value: strings.TrimSpace(albumArtist)},
		}
		if p.Year != "" {
			tp.Tags = append(tp.Tags, tags.Note{Field: tags.FieldDate, Value: p.Year})
		}
		p.Tracks = append(p.Tracks, tp)
	}

	albumDir := normalize.DirName(p.AlbumName)
	if albumDir == "" {
		albumDir = normalize.Name(p.AlbumName)
	}
	if short, cut := normalize.Truncate(albumDir, maxNameBytes); cut {
		p.Warnings = append(p.Warnings, fmt.Sprintf("album folder name was too long and has been shortened: %s -> %s", albumDir, short))
		albumDir = short
	}
	if albumDir == "" {
		p.Issues = append(p.Issues, Issue{Hard: true, Text: fmt.Sprintf("album name %q has no ASCII folder name; open the editor to supply one", p.AlbumName)})
	}
	p.AlbumDir = albumDir
	artistDir := artistKey.Dir
	if artistDir == "" {
		artistDir = normalize.DirName(p.AlbumArt)
	}
	if short, cut := normalize.Truncate(artistDir, maxNameBytes); cut {
		p.Warnings = append(p.Warnings, fmt.Sprintf("artist folder name was too long and has been shortened: %s -> %s", artistDir, short))
		artistDir = short
	}
	p.ArtistDir = artistDir
	if artistDir == "" {
		p.Issues = append(p.Issues, Issue{Hard: true, Text: fmt.Sprintf("album artist %q has no ASCII folder name; open the editor to supply one", p.AlbumArt)})
	}
	if artistDir != "" && albumDir != "" {
		p.ArchiveDir = filepath.Join(archiveRoot, artistDir, albumDir)
		p.LibraryDir = filepath.Join(libraryRoot, artistDir, albumDir)
	}
	return p
}

func quoteAll(in []string) []string {
	out := make([]string, 0, len(in))
	for _, s := range in {
		out = append(out, fmt.Sprintf("%q", s))
	}
	return out
}

func splitDirName(dir string) (artist, album string, ok bool) {
	name := strings.TrimSpace(dir)
	for _, open := range []string{"[", "("} {
		if i := strings.Index(name, open); i > 0 {
			closeCh := map[string]string{"[": "]", "(": ")"}[open]
			if j := strings.Index(name, closeCh); j > i && strings.TrimSpace(name[j+1:]) == "" {
				name = strings.TrimSpace(name[:i])
			}
		}
	}
	name = strings.TrimSpace(strings.TrimSuffix(name, "- flac"))
	name = strings.TrimSpace(strings.TrimSuffix(name, "- FLAC"))
	name = strings.TrimSpace(name)
	if name == "" {
		return "", "", false
	}

	if a, rest, found := strings.Cut(name, " - "); found {
		a, rest = strings.TrimSpace(a), strings.TrimSpace(rest)
		if a != "" && rest != "" {
			return a, rest, true
		}
	}
	return "", "", false
}

// noteCollisions records the names in a plan that cannot coexist.
//
// The first kind is two different titles collapsing to the same normalised text,
// which is worth stopping for because the title is the only human-readable part
// of a file name. The second is two tracks whose whole target is the same string,
// which the first check cannot see when they also share a track number, because
// it groups by title and folds repeats of a title together. That one is not a
// naming nuisance but a lost track: the copy truncates and replaces, so the album
// is filed one track short and every later check still passes.
func noteCollisions(p *Plan, titles, sources [][2]string) {
	for _, c := range normalize.DetectCollisions(titles) {
		p.Issues = append(p.Issues, Issue{Hard: true, Text: fmt.Sprintf("two different titles normalise to the same name %q (from %s); rename one before continuing",
			c.Target, strings.Join(quoteAll(c.Causes), " and "))})
	}
	for _, c := range normalize.TargetClashes(sources) {
		p.Issues = append(p.Issues, Issue{Hard: true, Text: fmt.Sprintf("%s would be written twice, from %s; give the tracks different numbers or titles, in their tags or in the staged file names",
			c.Target, strings.Join(quoteAll(c.Causes), " and "))})
	}
}

// titlePairs and sourcePairs are the two views noteCollisions needs: what the
// tracks are called, and which files they came from.
func titlePairs(tracks []TrackPlan) [][2]string {
	out := make([][2]string, 0, len(tracks))
	for _, t := range tracks {
		out = append(out, [2]string{t.Title, t.Target})
	}
	return out
}

func sourcePairs(tracks []TrackPlan) [][2]string {
	out := make([][2]string, 0, len(tracks))
	for _, t := range tracks {
		out = append(out, [2]string{filepath.Base(t.Source), t.Target})
	}
	return out
}

// Sheet returns the editable description of this plan: everything intake is
// about to write, in a form a person can change in $EDITOR.
func (p Plan) Sheet() sheet.Sheet {
	tracks := make([]sheet.Track, 0, len(p.Tracks))
	for i, t := range p.Tracks {
		artist := ""
		if v, ok := tags.Get(t.Tags, tags.FieldArtist); ok && strings.TrimSpace(v) != strings.TrimSpace(p.AlbumArt) {
			artist = strings.TrimSpace(v)
		}
		tracks = append(tracks, sheet.Track{
			ID:      i + 1,
			Title:   t.Title,
			Artist:  artist,
			Disc:    t.Disc,
			Number:  t.Number,
			Source:  filepath.Base(t.Source),
			Derived: t.Target,
		})
	}
	return sheet.Sheet{
		Album:       p.AlbumName,
		AlbumArtist: p.AlbumArt,
		ArtistDir:   p.ArtistDir,
		AlbumDir:    p.AlbumDir,
		Year:        p.Year,
		Tracks:      tracks,
	}
}

// ApplySheet rewrites the plan from an edited sheet and returns it to a state
// that can be filed: targets rebuilt, totals recounted, and every issue that was
// about a name worked out again from what the sheet now says.
//
// Tracks the sheet no longer mentions are dropped from the album. That is what
// makes "delete the block" mean something -- the old editor's comment claimed a
// deleted line left the file out, and it did not: the track was still filed,
// under the name intake had already chosen for it.
func (p *Plan) ApplySheet(s sheet.Sheet) error {
	before := p.Tracks
	kept := make([]TrackPlan, 0, len(s.Tracks))
	for _, st := range s.Tracks {
		if st.ID < 1 || st.ID > len(before) {
			return fmt.Errorf("track %d is not in this album (it has %d tracks)", st.ID, len(before))
		}
		tp := before[st.ID-1]
		tp.Disc = st.Disc
		tp.Number = st.Number
		tp.Title = strings.TrimSpace(st.Title)
		tp.Artist = strings.TrimSpace(st.Artist)
		if tp.Artist == "" {
			tp.Artist = strings.TrimSpace(s.AlbumArtist)
		}
		kept = append(kept, tp)
	}
	if len(kept) == 0 {
		return errors.New("no tracks left; the album would have nothing in it")
	}

	oldAlbum, oldArt := p.AlbumName, p.AlbumArt
	p.AlbumName = strings.TrimSpace(s.Album)
	p.AlbumTag = p.AlbumName
	p.AlbumArt = strings.TrimSpace(s.AlbumArtist)
	p.CreditFromTags = p.AlbumArt

	// A folder that still holds the name intake derived it from follows a
	// rename; one that was typed on purpose does not. Correcting "Boards of
	// Canad" to "Boards of Canada" should not leave the album sitting in
	// "boards-of-canad", and deliberately naming a folder something other than
	// the album should not be undone a moment later.
	albumDir := strings.TrimSpace(s.AlbumDir)
	if albumDir == "" || normalize.DirName(albumDir) == normalize.DirName(oldAlbum) {
		albumDir = p.AlbumName
	}
	artistDir := strings.TrimSpace(s.ArtistDir)
	if artistDir == "" || normalize.DirName(artistDir) == normalize.DirName(oldArt) {
		artistDir = p.AlbumArt
	}
	p.AlbumDir = normalize.DirName(albumDir)
	if p.AlbumDir == "" {
		p.AlbumDir = normalize.Name(albumDir)
	}
	p.ArtistDir = normalize.DirName(artistDir)
	if p.ArtistDir == "" {
		p.ArtistDir = normalize.Name(artistDir)
	}
	p.Year = tags.NormalizeYear(s.Year)
	if strings.TrimSpace(s.Year) != "" && p.Year == "" {
		p.Warnings = append(p.Warnings, fmt.Sprintf("could not read a year from %q", s.Year))
	}

	// A dropped or renumbered track changes the totals, and a stale TRACKTOTAL
	// is worse than none: players use it to tell a complete album from a
	// half-finished download.
	maxTrack := 0
	for i := range kept {
		if kept[i].Number > maxTrack {
			maxTrack = kept[i].Number
		}
	}
	width := normalize.PadWidth(maxTrack)
	if p.Width > width {
		width = p.Width
	}
	discs := map[int]bool{}
	for _, t := range kept {
		discs[t.Disc] = true
	}
	withDisc := useDiscPrefix(p.DiscPrefix, len(discs))

	for i := range kept {
		name := kept[i].Title
		override := strings.TrimSpace(s.Tracks[i].File)
		if override != "" {
			name = strings.ReplaceAll(filepath.Base(override), string(filepath.Separator), "-")
			if name == "." || name == ".." {
				return fmt.Errorf("track %d would be written to %q", s.Tracks[i].ID, name)
			}
			if filepath.Ext(name) == "" {
				name += kept[i].Ext
			}
			kept[i].Target = name
			kept[i].Title = titleFromFile(name)
		} else {
			kept[i].Target = normalize.TrackFile(kept[i].Disc, kept[i].Number, width, kept[i].Title, kept[i].Ext, withDisc)
		}
		if n, cut := normalize.Truncate(kept[i].Target, maxNameBytes); cut {
			kept[i].Target = n
			kept[i].Truncated = true
		} else {
			kept[i].Truncated = false
		}
	}
	p.Tracks = kept
	p.retotal()

	for i := range p.Tracks {
		t := &p.Tracks[i]
		t.Tags = setTag(t.Tags, tags.FieldTrackNumber, fmt.Sprintf("%d", t.Number))
		t.Tags = setTag(t.Tags, tags.FieldDiscNumber, fmt.Sprintf("%d", t.Disc))
		t.Tags = setTag(t.Tags, tags.FieldTitle, t.Title)
		t.Tags = setTag(t.Tags, tags.FieldAlbum, p.AlbumName)
		t.Tags = setTag(t.Tags, tags.FieldArtist, t.Artist)
		t.Tags = setTag(t.Tags, tags.FieldAlbumArtist, p.AlbumArt)
		t.Tags = setTag(t.Tags, tags.FieldDate, p.Year)
	}

	p.rebuildPaths()
	p.reassessAfterEdit()
	noteCollisions(p, titlePairs(p.Tracks), sourcePairs(p.Tracks))
	return nil
}

// retotal recounts the per-disc track totals and the disc total.
func (p *Plan) retotal() {
	perDisc := map[int]int{}
	for _, t := range p.Tracks {
		perDisc[t.Disc]++
	}
	for i := range p.Tracks {
		t := &p.Tracks[i]
		n := fmt.Sprintf("%d", perDisc[t.Disc])
		t.Tags = setTag(t.Tags, tags.FieldTrackTotal, n)
		t.Tags = setTag(t.Tags, tags.FieldLegacyTrackTotal, n)
		d := fmt.Sprintf("%d", len(perDisc))
		t.Tags = setTag(t.Tags, tags.FieldDiscTotal, d)
		t.Tags = setTag(t.Tags, tags.FieldLegacyDiscTotal, d)
	}
}

// setTag replaces a tag, adds it, or removes it when the value is empty.
func setTag(notes []tags.Note, field, value string) []tags.Note {
	for i := range notes {
		if strings.EqualFold(notes[i].Field, field) {
			if value == "" {
				return append(notes[:i], notes[i+1:]...)
			}
			notes[i].Value = value
			return notes
		}
	}
	if value == "" {
		return notes
	}
	return append(notes, tags.Note{Field: field, Value: value})
}

// titleFromFile is the reverse of the naming rule, for a hand-typed file name.
func titleFromFile(name string) string {
	s := strings.TrimSuffix(name, filepath.Ext(name))
	if i := strings.IndexByte(s, '_'); i >= 0 {
		s = s[i+1:]
	}
	return strings.TrimSpace(strings.ReplaceAll(s, "-", " "))
}

// reassessAfterEdit works out the name issues again from what the plan now says,
// rather than from what the tags originally said. Clearing and re-adding is the
// point: an issue that the edit fixed has to disappear, or the album stays
// blocked by a complaint about metadata that is no longer there.
func (p *Plan) reassessAfterEdit() {
	for _, text := range []string{
		"album name is unknown",
		"album name is empty",
		"album artist is unknown",
		"album artist is empty",
		"no ASCII folder name",
		"no usable title",
		"normalise to the same name",
		"would be written twice",
	} {
		p.Issues = removeIssues(p.Issues, text)
	}
	if p.AlbumName == "" {
		p.Issues = append(p.Issues, Issue{Hard: true, Text: "the album has no name; put one in the album sheet"})
	}
	if p.AlbumArt == "" {
		p.Issues = append(p.Issues, Issue{Hard: true, Text: "the album has no artist; put one in the album sheet"})
	}
	if p.AlbumDir == "" {
		p.Issues = append(p.Issues, Issue{Hard: true, Text: fmt.Sprintf("album name %q has no ASCII folder name; put one in the album sheet", p.AlbumName)})
	}
	if p.ArtistDir == "" {
		p.Issues = append(p.Issues, Issue{Hard: true, Text: fmt.Sprintf("album artist %q has no ASCII folder name; put one in the album sheet", p.AlbumArt)})
	}
	for _, t := range p.Tracks {
		if strings.TrimSpace(t.Title) == "" {
			p.Issues = append(p.Issues, Issue{Hard: true, Text: fmt.Sprintf("%s: no usable title; put one in the album sheet", filepath.Base(t.Source))})
		}
	}
}

// BuildWithArtist builds the plan again with the artist folder that was
// resolved (or chosen) rather than the one the tags implied.
func BuildWithArtist(a scan.Album, archiveRoot, libraryRoot string, key DirKey, discPrefix string) Plan {
	p := Build(a, archiveRoot, libraryRoot, key, discPrefix)
	if key.Dir != "" {
		p.ArtistDir = key.Dir
	}
	if strings.TrimSpace(key.Credit) != "" {
		p.AlbumArt = key.Credit
		p.CreditFromTags = key.Credit
		for i := range p.Tracks {
			p.Tracks[i].Tags = setTag(p.Tracks[i].Tags, tags.FieldAlbumArtist, key.Credit)
			if v, ok := tags.Get(p.Tracks[i].Tags, tags.FieldArtist); !ok || strings.TrimSpace(v) == "" {
				p.Tracks[i].Tags = setTag(p.Tracks[i].Tags, tags.FieldArtist, key.Credit)
			}
		}
	}
	p.rebuildPaths()
	noteCollisions(&p, titlePairs(p.Tracks), sourcePairs(p.Tracks))
	return p
}

func (p *Plan) rebuildPaths() {
	if p.AlbumDir == "" {
		p.AlbumDir = normalize.DirName(p.AlbumName)
		if p.AlbumDir == "" {
			p.AlbumDir = normalize.Name(p.AlbumName)
		}
	}
	if p.ArtistDir == "" {
		p.ArtistDir = normalize.DirName(p.AlbumArt)
	}
	if p.ArchiveRoot == "" || p.LibraryRoot == "" {
		return
	}
	if p.ArtistDir != "" && p.AlbumDir != "" {
		p.ArchiveDir = filepath.Join(p.ArchiveRoot, p.ArtistDir, p.AlbumDir)
		p.LibraryDir = filepath.Join(p.LibraryRoot, p.ArtistDir, p.AlbumDir)
	}
}

func removeIssues(in []Issue, contains string) []Issue {
	out := make([]Issue, 0, len(in))
	for _, i := range in {
		if !strings.Contains(i.Text, contains) {
			out = append(out, i)
		}
	}
	return out
}

func commonValue(a scan.Album, field string) (string, bool) {
	var value string
	found := false
	for _, t := range a.Tracks {
		v, ok := tags.Get(t.Tags, field)
		if !ok || strings.TrimSpace(v) == "" {
			return "", false
		}
		if !found {
			value, found = v, true
			continue
		}
		if v != value {
			return "", false
		}
	}
	return value, found
}

// dominantArtist returns the most common non-empty ARTIST across an album's
// tracks, how many tracks carry it, and how many carry any artist at all.
//
// This is how an album with guest tracks is told apart from a compilation when
// there is no ALBUMARTIST to say so. Matching whole credit strings is deliberate:
// "Deadmau5 + Imogen Heap" is a different credit from "Deadmau5", and a solo
// album with two features still has a clear majority. Splitting credits on a
// separator would mean guessing whether it is "+", "&", "feat." or "with".
func dominantArtist(a scan.Album) (string, int, int) {
	return dominantValue(a, tags.FieldArtist)
}

// dominantValue returns the most common non-empty value of a field, how many
// tracks carry it, and how many carry any value at all. Ties break
// alphabetically so the result does not depend on map order.
func dominantValue(a scan.Album, field string) (string, int, int) {
	counts := map[string]int{}
	total := 0
	for _, t := range a.Tracks {
		v, ok := tags.Get(t.Tags, field)
		v = strings.TrimSpace(v)
		if !ok || v == "" {
			continue
		}
		counts[v]++
		total++
	}
	best, n := "", 0
	for v, c := range counts {
		if c > n || (c == n && v < best) {
			best, n = v, c
		}
	}
	return best, n, total
}

// differingArtists reports whether the tracks credit more than one artist.
func differingArtists(a scan.Album) bool {
	first := ""
	for _, t := range a.Tracks {
		v, ok := tags.Get(t.Tags, tags.FieldArtist)
		v = strings.TrimSpace(v)
		if !ok || v == "" {
			continue
		}
		if first == "" {
			first = v
			continue
		}
		if v != first {
			return true
		}
	}
	return false
}

// useDiscPrefix decides whether target names carry the disc number. "auto" only
// carries it when there is more than one disc, where it is the only thing
// separating two tracks that share a number.
func useDiscPrefix(mode string, discs int) bool {
	switch strings.ToLower(strings.TrimSpace(mode)) {
	case "never":
		return false
	case "auto":
		return discs > 1
	default:
		return true
	}
}