# detect-platform.ps1 - Detect git platform (Gitea or GitHub) for current repo
# Usage: . .\detect-platform.ps1; Get-GitPlatform
#        or: .\detect-platform.ps1 (prints platform name)

function Get-GitPlatform {
    [CmdletBinding()]
    param()

    $remoteUrl = git remote get-url origin 2>$null

    if ([string]::IsNullOrEmpty($remoteUrl)) {
        Write-Error "Not a git repository or no origin remote"
        return $null
    }

    # Check for GitHub
    if ($remoteUrl -match "github\.com") {
        return "github"
    }

    # Check for common Gitea indicators
    # Gitea URLs typically don't contain github.com, gitlab.com, bitbucket.org
    if ($remoteUrl -notmatch "gitlab\.com" -and $remoteUrl -notmatch "bitbucket\.org") {
        # Assume Gitea for self-hosted repos
        return "gitea"
    }

    return "unknown"
}

function Get-GitRepoInfo {
    [CmdletBinding()]
    param()

    $remoteUrl = git remote get-url origin 2>$null

    if ([string]::IsNullOrEmpty($remoteUrl)) {
        Write-Error "Not a git repository or no origin remote"
        return $null
    }

    # Extract owner/repo from URL
    # Handles: git@host:owner/repo.git, https://host/owner/repo.git, https://host/owner/repo
    $repoPath = $remoteUrl
    if ($remoteUrl -match "^git@") {
        $repoPath = ($remoteUrl -split ":")[1]
    } else {
        # Remove protocol and host
        $repoPath = $remoteUrl -replace "^https?://[^/]+/", ""
    }

    # Remove .git suffix if present
    $repoPath = $repoPath -replace "\.git$", ""

    return $repoPath
}

function Get-GitRemoteHost {
    [CmdletBinding()]
    param()

    $remoteUrl = git remote get-url origin 2>$null

    if ([string]::IsNullOrEmpty($remoteUrl)) {
        Write-Error "Not a git repository or no origin remote"
        return $null
    }

    if ($remoteUrl -match "^https?://([^/]+)/") {
        $remoteHost = $Matches[1]
        return ($remoteHost -replace "^.*@", "")
    }

    if ($remoteUrl -match "^git@([^:]+):") {
        return $Matches[1]
    }

    return $null
}

function Get-TeaLoginList {
    [CmdletBinding()]
    param()

    $json = tea login list --output json 2>$null
    if (-not $json) {
        return @()
    }

    try {
        $items = $json | ConvertFrom-Json
    } catch {
        return @()
    }

    if ($null -eq $items) {
        return @()
    }

    return @($items)
}

function Test-GiteaUrlMatchesHost {
    [CmdletBinding()]
    param(
        [string]$Url,
        [string]$GiteaHost
    )

    if ([string]::IsNullOrEmpty($Url) -or [string]::IsNullOrEmpty($GiteaHost)) {
        return $false
    }

    try {
        $uri = [Uri]$Url
        return $uri.Host -eq $GiteaHost
    } catch {
        return $false
    }
}

function Find-TeaLoginForHost {
    [CmdletBinding()]
    param([Parameter(Mandatory=$true)][string]$GiteaHost)

    foreach ($login in Get-TeaLoginList) {
        $name = if ($login.name) { [string]$login.name } elseif ($login.Name) { [string]$login.Name } else { "" }
        $url = if ($login.url) { [string]$login.url } elseif ($login.URL) { [string]$login.URL } else { "" }
        if ([string]::IsNullOrEmpty($name) -or [string]::IsNullOrEmpty($url)) {
            continue
        }

        try {
            $uri = [Uri]$url
            if ($uri.Host -eq $GiteaHost) {
                return $name
            }
        } catch {
            continue
        }
    }

    return $null
}

function Test-TeaLoginMatchesHost {
    [CmdletBinding()]
    param(
        [Parameter(Mandatory=$true)][string]$LoginName,
        [Parameter(Mandatory=$true)][string]$GiteaHost
    )

    foreach ($login in Get-TeaLoginList) {
        $name = if ($login.name) { [string]$login.name } elseif ($login.Name) { [string]$login.Name } else { "" }
        $url = if ($login.url) { [string]$login.url } elseif ($login.URL) { [string]$login.URL } else { "" }
        if ($name -ne $LoginName -or [string]::IsNullOrEmpty($url)) {
            continue
        }

        try {
            $uri = [Uri]$url
            return $uri.Host -eq $GiteaHost
        } catch {
            return $false
        }
    }

    return $false
}

function Get-GiteaLoginForHost {
    [CmdletBinding()]
    param([string]$GiteaHost)

    if ([string]::IsNullOrEmpty($GiteaHost)) {
        $GiteaHost = Get-GitRemoteHost
    }
    if ([string]::IsNullOrEmpty($GiteaHost)) {
        return $null
    }

    if ($env:GITEA_LOGIN) {
        if (Test-TeaLoginMatchesHost -LoginName $env:GITEA_LOGIN -GiteaHost $GiteaHost) {
            return $env:GITEA_LOGIN
        }
    }

    return Find-TeaLoginForHost -GiteaHost $GiteaHost
}

function Get-GiteaRepoArgs {
    [CmdletBinding()]
    param()

    $repo = Get-GitRepoInfo
    $hostName = Get-GitRemoteHost
    $login = Get-GiteaLoginForHost -GiteaHost $hostName

    if ([string]::IsNullOrEmpty($repo) -or [string]::IsNullOrEmpty($login)) {
        return @()
    }

    return @("--repo", $repo, "--login", $login)
}

function Get-GitRepoOwner {
    [CmdletBinding()]
    param()

    $repoInfo = Get-GitRepoInfo
    if ($repoInfo) {
        return ($repoInfo -split "/")[0]
    }
    return $null
}

function Get-GitRepoName {
    [CmdletBinding()]
    param()

    $repoInfo = Get-GitRepoInfo
    if ($repoInfo) {
        return ($repoInfo -split "/")[-1]
    }
    return $null
}

# If script is run directly (not dot-sourced), output the platform
if ($MyInvocation.InvocationName -ne ".") {
    Get-GitPlatform
}
