import Foundation
import Testing
@testable import Kanban

/// **Where the app's commits get their author from** (06-history-undo.md ▸ Interaction with external
/// writers ▸ "Where the user's git identity comes from"): repo-local `.git/config` when it names
/// one, the derived `Full Name <shortname@hostname>` default when it doesn't.
///
/// Both halves are pure functions here on purpose. The derivation takes its three strings as
/// arguments rather than reading the machine, so the *shape* is provable on any machine — including
/// one whose account has no full name, which is the case the fallbacks exist for. And the config
/// read is a parse over text, so the format's edges (comments, quoting, subsections, a `[user]`
/// section that never appears) are pinned without a repository. The write side (`GitConfigFile
/// .applying`) is pinned the same way: a pure function over text, so every rule in 06's "Writes
/// append, reads take the last" paragraph is provable without a repository either.

@Suite("Git identity ▸ the derived default")
struct GitIdentityDerivationTests {

    @Test("The shape is the account's full name plus shortname@hostname")
    func theDerivedShape() {
        let identity = GitIdentity.derived(fullName: "Ada Lovelace", accountName: "ada", hostName: "analytical.local")

        #expect(identity.name == "Ada Lovelace")
        #expect(identity.email == "ada@analytical.local")
    }

    @Test("An account with no full name falls back to its short name rather than committing as \"\"")
    func anEmptyFullNameFallsBack() {
        let identity = GitIdentity.derived(fullName: "   ", accountName: "ada", hostName: "analytical.local")

        #expect(identity.name == "ada")
        #expect(identity.email == "ada@analytical.local")
    }

    @Test("Characters an address may not carry are collapsed, not passed to libgit2")
    func addressComponentsAreSanitized() {
        // libgit2 refuses a signature carrying a space or an angle bracket outright — the commit
        // fails rather than looking odd — so this is a correctness fallback, not cosmetics.
        let identity = GitIdentity.derived(
            fullName: "Ada Lovelace",
            accountName: "ada lovelace",
            hostName: "Ada's <Mac>.local"
        )

        #expect(!identity.email.contains(" "))
        #expect(!identity.email.contains("<"))
        #expect(!identity.email.contains(">"))
        #expect(identity.email == "ada-lovelace@Ada-s--Mac-.local")
    }

    @Test("A machine with no name reads localhost, and an account with none reads user")
    func emptyComponentsHaveHonestFallbacks() {
        let identity = GitIdentity.derived(fullName: "", accountName: "", hostName: "")

        #expect(identity.name == "Lanework")
        #expect(identity.email == "user@localhost")
    }

    @Test("A trailing dot on a fully-qualified host name is dropped")
    func aTrailingDotIsDropped() {
        let identity = GitIdentity.derived(fullName: "Ada", accountName: "ada", hostName: "host.example.com.")

        #expect(identity.email == "ada@host.example.com")
    }

    @Test("This machine's derived default is well-formed, whatever this machine is called")
    func theMachineDefaultIsWellFormed() {
        let identity = GitIdentity.derivedDefault()

        #expect(!identity.name.isEmpty)
        #expect(identity.email.contains("@"))
        #expect(!identity.email.contains(" "))
    }
}

@Suite("Git identity ▸ repo-local config wins")
struct GitConfigFileTests {

    @Test("A `[user]` section supplies both halves")
    func bothKeysAreRead() {
        let text = """
        [core]
        \trepositoryformatversion = 0
        [user]
        \tname = Ada Lovelace
        \temail = ada@example.com
        """

        let identity = GitConfigFile.identity(inConfigText: text)
        #expect(identity.name == "Ada Lovelace")
        #expect(identity.email == "ada@example.com")
    }

    @Test("Config wins over the derived default, key by key")
    func resolutionPrefersConfigPerKey() {
        let derived = GitIdentity(name: "Machine Owner", email: "owner@mac.local")

        let both = GitIdentity.resolve(repoLocal: (name: "Ada", email: "ada@example.com"), derived: derived)
        #expect(both == GitIdentity(name: "Ada", email: "ada@example.com"))

        // Half-configured is a real state — it is what a `git config user.email` typo leaves — and
        // git resolves each key on its own.
        let nameOnly = GitIdentity.resolve(repoLocal: (name: "Ada", email: nil), derived: derived)
        #expect(nameOnly == GitIdentity(name: "Ada", email: "owner@mac.local"))

        let neither = GitIdentity.resolve(repoLocal: (name: nil, email: "  "), derived: derived)
        #expect(neither == derived, "a blank value is not a value")
    }

    @Test("Comments and quoting are read the way git reads them")
    func theParseHandlesTheFormatsEdges() {
        let text = """
        # a comment
        ; another
        [user]
        \tname = "Ada # Lovelace"
        \temail = ada@example.com # trailing comment
        """

        let identity = GitConfigFile.identity(inConfigText: text)
        #expect(identity.name == "Ada # Lovelace", "a `#` inside quotes is content")
        #expect(identity.email == "ada@example.com", "an unquoted trailing comment is not")
    }

    @Test("Reads take the last plain-section value, and no subsection's")
    func readsTakeTheLastPlainSectionValue() {
        // **Writes append, reads take the last** (06 ▸ Interaction with external writers, blessed
        // 2026-07-31): "the reader — like git itself — takes the last plain-section value, which is
        // exactly what an append produces."
        let appended = """
        [user]
        \tname = Old Ada
        \temail = old@example.com
        [user]
        \tname = New Ada
        \temail = new@example.com
        """
        #expect(GitConfigFile.identity(inConfigText: appended).name == "New Ada")
        #expect(GitConfigFile.identity(inConfigText: appended).email == "new@example.com")

        // A subsection is a *different key* in git's model — `user.work.name`, not `user.name` — so
        // it is not an answer to this question however late in the file it sits. Signing the user's
        // commits with an identity they filed under a name this app never asked about would be the
        // worse error, and 06 says plain-section for exactly that reason.
        let subsectioned = """
        [user]
        \tname = Ada
        \temail = ada@example.com
        [user "work"]
        \tname = Work Ada
        \temail = ada@work.example
        """
        #expect(GitConfigFile.identity(inConfigText: subsectioned).name == "Ada")
        #expect(GitConfigFile.identity(inConfigText: subsectioned).email == "ada@example.com")

        // A file with *only* a subsection names nobody, and falls through to the derived default.
        let onlySubsection = "[user \"work\"]\n\tname = Work Ada\n\temail = ada@work.example\n"
        #expect(GitConfigFile.identity(inConfigText: onlySubsection) == (nil, nil))
    }

    @Test("A config with no `[user]` section, or no config at all, names nobody")
    func absentConfigNamesNobody() throws {
        let empty = GitConfigFile.identity(inConfigText: "[core]\n\tbare = false\n")
        #expect(empty.name == nil)
        #expect(empty.email == nil)

        let fixture = try WriterFixture()
        defer { fixture.tearDown() }
        let missing = GitConfigFile.identity(inGitDirectory: fixture.root.appendingPathComponent(".git"))
        #expect(missing.name == nil)
        #expect(missing.email == nil)
    }

    @Test("The file on disk is what is read — the board root's own `.git/config`")
    func theFileIsRead() throws {
        let fixture = try WriterFixture()
        defer { fixture.tearDown() }
        try fixture.file(".git/config", Data("[user]\n\tname = Ada\n\temail = ada@example.com\n".utf8))

        let identity = GitConfigFile.identity(inGitDirectory: fixture.root.appendingPathComponent(".git"))
        #expect(identity.name == "Ada")
        #expect(identity.email == "ada@example.com")
    }
}

/// **The write side** (06-history-undo.md ▸ Interaction with external writers, "Where the user's
/// git identity comes from"; the clear rule ruled 2026-08-06): a set is append-only — it never edits
/// or deletes an existing line, appending one new plain `[user]` section instead, even over an
/// already-populated file — and a clear is the one sanctioned in-place edit, deleting every matching
/// line in every plain `[user]` section and dropping any header left empty. Both halves resolve
/// against the current parse first, so a call that would change nothing is a true no-op.
@Suite("Git identity ▸ writing repo-local config")
struct GitConfigFileWriteTests {

    @Test("A set never edits an existing line — it appends a new section, and the old line survives verbatim")
    func setAppendsRatherThanEditing() {
        // Weird indentation and an inline comment: exactly the shape a set must leave untouched.
        let original = "[user]\n     name = Old Name    # keep me, weird spacing and all\n"

        let written = GitConfigFile.applying(name: "New Name", email: "new@example.com", to: original)

        #expect(
            written.contains("     name = Old Name    # keep me, weird spacing and all"),
            "the original line survives byte-for-byte"
        )
        #expect(written.contains("\tname = New Name"), "the set lands in a freshly appended section")
        #expect(written.contains("\temail = new@example.com"))
        #expect(
            written.components(separatedBy: "[user]").count - 1 == 2,
            "a second `[user]` header was appended, not merged into the first"
        )

        let read = GitConfigFile.identity(inConfigText: written)
        #expect(read.name == "New Name", "last-wins reading is what makes the appended value win")
        #expect(read.email == "new@example.com")
    }

    @Test("Setting a key to its already-current value is a true no-op — byte-identical, no growth")
    func settingTheCurrentValueIsANoOp() {
        let text = "[user]\n\tname = Ada Lovelace\n\temail = ada@example.com\n"

        let written = GitConfigFile.applying(name: "Ada Lovelace", email: "ada@example.com", to: text)
        #expect(written == text)

        // Whitespace around an unchanged value still resolves to the same target, so it is still a
        // no-op — the comparison is on trimmed content, not on the caller's exact bytes.
        let paddedTarget = GitConfigFile.applying(name: "  Ada Lovelace  ", email: " ada@example.com ", to: text)
        #expect(paddedTarget == text)
    }

    @Test("Clearing an absent key returns byte-identical text")
    func clearingAnAbsentKeyIsANoOp() {
        let text = "[user]\n\tname = Ada\n"

        let written = GitConfigFile.applying(name: "Ada", email: nil, to: text)
        #expect(written == text)
    }

    @Test("A clear deletes every occurrence across two plain `[user]` sections, and reads back nil")
    func clearDeletesEveryOccurrence() {
        let text = """
        [user]
        \temail = ada@one.example
        [core]
        \tbare = false
        [user]
        \temail = ada@two.example

        """

        // `name` is already absent everywhere, so passing `nil` for it is a no-op; only `email` is
        // genuine pending work, and it must be cleared from *both* plain sections, not just the last.
        let written = GitConfigFile.applying(name: nil, email: "", to: text)

        #expect(!written.contains("email"), "no occurrence survives, in either section")
        #expect(written.contains("\tbare = false"), "an unrelated section is untouched")
        #expect(GitConfigFile.identity(inConfigText: written).email == nil)
    }

    @Test("Clearing both keys drops every emptied `[user]` header, but keeps one that still has signingkey")
    func clearingDropsOnlyTrulyEmptyHeaders() {
        let text = """
        [user]
        \tname = Ada
        [user]
        \temail = ada@example.com
        [user]
        \tname = Ada C
        \temail = adac@example.com
        \tsigningkey = ABC123

        """

        let written = GitConfigFile.applying(name: "", email: nil, to: text)

        #expect(!written.contains("name ="), "no name line remains anywhere")
        #expect(!written.contains("email ="), "no email line remains anywhere")
        #expect(written.contains("\tsigningkey = ABC123"), "a key this app has no opinion about survives")
        #expect(
            written.components(separatedBy: "[user]").count - 1 == 1,
            "the two now-empty headers are dropped; the section keeping signingkey keeps its header"
        )
        #expect(GitConfigFile.identity(inConfigText: written) == (nil, nil))
    }

    @Test("A combined set-and-clear call clears in place, then appends the set section")
    func combinedSetAndClear() {
        let original = """
        [user]
        \tname = Old Name
        \temail = old@example.com

        """

        let written = GitConfigFile.applying(name: "New Name", email: "", to: original)

        #expect(written.contains("\tname = Old Name"), "the set never deletes the line it is replacing")
        #expect(written.contains("\tname = New Name"), "the set lands in an appended section")
        #expect(!written.contains("email"), "the clear deletes the email line in place, nothing appended for it")

        let read = GitConfigFile.identity(inConfigText: written)
        #expect(read.name == "New Name")
        #expect(read.email == nil)
    }

    @Test("A `[user \"work\"]` subsection is untouched by a set or a clear, and never leaks into a read")
    func subsectionsAreUntouchable() {
        let original = """
        [user "work"]
        \tname = Work Ada
        \temail = ada@work.example
        [user]
        \tname = Home Ada
        \temail = ada@home.example

        """
        #expect(GitConfigFile.identity(inConfigText: original).name == "Home Ada", "the subsection is not read")

        let cleared = GitConfigFile.applying(name: "", email: "", to: original)
        #expect(cleared.contains("[user \"work\""), "the subsection header survives")
        #expect(cleared.contains("\tname = Work Ada"), "the subsection's own keys are untouched by a clear")
        #expect(cleared.contains("\temail = ada@work.example"))
        #expect(!cleared.contains("[user]"), "the plain section is what a clear may empty out")
        #expect(GitConfigFile.identity(inConfigText: cleared) == (nil, nil), "the subsection never leaks into a read")

        let written = GitConfigFile.applying(name: "New Home Ada", email: "new@home.example", to: original)
        #expect(written.contains("[user \"work\""), "the subsection header survives a set too")
        #expect(written.contains("\tname = Work Ada"), "the subsection's own keys are untouched by a set")
        #expect(written.contains("\tname = Home Ada"), "the old plain section survives verbatim — sets never edit")
        let read = GitConfigFile.identity(inConfigText: written)
        #expect(read.name == "New Home Ada", "the appended section wins by last-wins, never the subsection")
        #expect(read.email == "new@home.example")
    }

    @Test("Writing into empty text creates just the new `[user]` section")
    func writesIntoAnEmptyConfig() {
        let written = GitConfigFile.applying(name: "Ada Lovelace", email: "ada@example.com", to: "")

        #expect(written == "[user]\n\tname = Ada Lovelace\n\temail = ada@example.com\n")
        let read = GitConfigFile.identity(inConfigText: written)
        #expect(read.name == "Ada Lovelace")
        #expect(read.email == "ada@example.com")
    }

    @Test("Trailing-newline shape: a clear preserves it, a set's append normalizes it")
    func trailingNewlineRoundTrip() {
        // Clearing is a pure line deletion — it must not add a trailing newline that was never there.
        let withoutTrailingNewline = "[user]\n\tname = Ada\n\temail = ada@example.com"
        let clearedNoTrailingNewline = GitConfigFile.applying(name: "Ada", email: nil, to: withoutTrailingNewline)
        #expect(clearedNoTrailingNewline == "[user]\n\tname = Ada", "no trailing newline was introduced")

        // ...and must not drop one that was.
        let withTrailingNewline = "[user]\n\tname = Ada\n\temail = ada@example.com\n[core]\n\tbare = false\n"
        let clearedWithTrailingNewline = GitConfigFile.applying(name: "Ada", email: nil, to: withTrailingNewline)
        #expect(clearedWithTrailingNewline.hasSuffix("\tbare = false\n"), "the file's own trailing newline survives")

        // A set's append always lands the current code's shape (blank-line separator, one trailing
        // newline) whether or not the original file ended in one.
        let appendedNoTrailingNewline = GitConfigFile.applying(name: "Ada", email: "ada@example.com", to: "[core]\n\tbare = false")
        let appendedWithTrailingNewline = GitConfigFile.applying(name: "Ada", email: "ada@example.com", to: "[core]\n\tbare = false\n")
        #expect(appendedNoTrailingNewline == "[core]\n\tbare = false\n\n[user]\n\tname = Ada\n\temail = ada@example.com\n")
        #expect(appendedWithTrailingNewline == appendedNoTrailingNewline, "the trailing-newline state of the input doesn't change the appended shape")
    }
}
