2026-11-20 05:29:27 +00:00
package app
import (
"context"
"errors"
"fmt"
"os"
"path/filepath"
"strings"
"gitea.maximumdirect.net/eric/narratio/internal/adapters/storage"
"gitea.maximumdirect.net/eric/narratio/internal/artifacts"
"gitea.maximumdirect.net/eric/narratio/internal/config"
"go.maximumdirect.net/commandkit"
)
type sessionInitializationInput struct {
Selection configurationSelection
PreviousSessionID , Date , Title , Output , AudioS3Prefix , AudioDir string
Remote , Force bool
}
type sessionInitializationReport struct {
Campaign string ` json:"campaign" `
SessionID string ` json:"session_id" `
Destination string ` json:"destination" `
Remote bool ` json:"remote" `
Written bool ` json:"written" `
}
func checkSessionInitializationInput ( input * sessionInitializationInput ) error {
if err := checkConfigurationSelection ( input . Selection ) ; err != nil {
return err
}
if input . Selection . Session . Value == "" {
return fmt . Errorf ( "session identity is required" )
}
if ( strings . TrimSpace ( input . Output ) == "" ) == ! input . Remote {
return fmt . Errorf ( "specify exactly one target: --output or --remote" )
}
if strings . TrimSpace ( input . AudioDir ) != "" && strings . TrimSpace ( input . AudioS3Prefix ) != "" {
return fmt . Errorf ( "--audio-dir and --audio-s3-prefix are mutually exclusive" )
}
if strings . TrimSpace ( input . AudioDir ) != "" {
resolved , err := filepath . Abs ( input . AudioDir )
if err != nil {
return err
}
input . AudioDir = resolved
}
return nil
}
func sessionInitializationCommand ( deps commandDependencies ) commandkit . Command {
common := newConfigurationFlags ( func ( input * * sessionInitializationInput ) * configurationSelection { return & ( * input ) . Selection } )
return commandkit . NewCommand ( commandkit . CommandSpec [ * sessionInitializationInput ] { Name : "init" , Summary : "Create standalone local or remote session configuration." , NewInput : func ( ) * sessionInitializationInput { return & sessionInitializationInput { } } ,
Flags : [ ] commandkit . Flag [ * sessionInitializationInput ] { common . Config , common . Overlay , common . Campaign , common . CampaignFile , common . SecretsDir ,
commandkit . ValueFlag ( commandkit . FlagMeta { Name : "previous-session-id" , Usage : "Previous session identity." } , nil , stringValue , func ( input * * sessionInitializationInput , value commandkit . Supplied [ string ] ) {
( * input ) . PreviousSessionID = value . Value
} ) ,
commandkit . ValueFlag ( commandkit . FlagMeta { Name : "date" , Usage : "Session date." } , nil , stringValue , func ( input * * sessionInitializationInput , value commandkit . Supplied [ string ] ) {
( * input ) . Date = value . Value
} ) ,
commandkit . ValueFlag ( commandkit . FlagMeta { Name : "title" , Usage : "Session title." } , nil , stringValue , func ( input * * sessionInitializationInput , value commandkit . Supplied [ string ] ) {
( * input ) . Title = value . Value
} ) ,
commandkit . ValueFlag ( commandkit . FlagMeta { Name : "output" , Usage : "Local output YAML file." } , nil , stringValue , func ( input * * sessionInitializationInput , value commandkit . Supplied [ string ] ) {
( * input ) . Output = value . Value
} ) ,
commandkit . ValueFlag ( commandkit . FlagMeta { Name : "audio-s3-prefix" , Usage : "Session audio prefix in object storage." } , nil , stringValue , func ( input * * sessionInitializationInput , value commandkit . Supplied [ string ] ) {
( * input ) . AudioS3Prefix = value . Value
} ) ,
commandkit . ValueFlag ( commandkit . FlagMeta { Name : "audio-dir" , Usage : "Local audio directory, relative to the invocation directory." } , nil , stringValue , func ( input * * sessionInitializationInput , value commandkit . Supplied [ string ] ) {
( * input ) . AudioDir = value . Value
} ) ,
commandkit . BoolFlag ( commandkit . FlagMeta { Name : "remote" , Usage : "Create session configuration in object storage." } , false , func ( input * * sessionInitializationInput , value commandkit . Supplied [ bool ] ) {
( * input ) . Remote = value . Value
} ) ,
commandkit . BoolFlag ( commandkit . FlagMeta { Name : "force" , Usage : "Overwrite an existing target." } , false , func ( input * * sessionInitializationInput , value commandkit . Supplied [ bool ] ) {
( * input ) . Force = value . Value
} ) ,
} ,
Arguments : [ ] commandkit . Argument [ * sessionInitializationInput ] { commandkit . ValueArgument ( commandkit . ArgumentMeta { Name : "SESSION" , Usage : "New session identity." } , true , stringValue , func ( input * * sessionInitializationInput , value commandkit . Supplied [ string ] ) {
( * input ) . Selection . Session = value
} ) } ,
CheckInput : checkSessionInitializationInput ,
Run : func ( invocation commandkit . Invocation , input * sessionInitializationInput ) commandkit . Outcome {
2026-11-20 05:59:09 +00:00
report , err := initializeSession ( invocation . Context , input , withCommandReporting ( deps , invocation ) )
2026-11-20 05:29:27 +00:00
if report != nil {
err = errors . Join ( err , invocation . Reporter ( ) . Report ( commandkit . Report { Value : report } ) )
}
return operationOutcome ( err )
} ,
} )
}
func initializeSession ( ctx context . Context , request * sessionInitializationInput , deps commandDependencies ) ( report * sessionInitializationReport , err error ) {
deps = normalizeCommandDependencies ( deps )
deps . secretsBootstrap = & secretsBootstrap { }
sessionID , previousSessionID , date , title , output , audioS3Prefix , audioDir := request . Selection . Session . Value , request . PreviousSessionID , request . Date , request . Title , request . Output , request . AudioS3Prefix , request . AudioDir
remote , force := request . Remote , request . Force
acquired := newConfigurationAcquisition ( request . Selection , deps )
defer func ( ) { err = errors . Join ( err , acquired . Close ( ) ) } ( )
pipeline , err := acquired . Pipeline ( ctx )
if err != nil {
return nil , err
}
campaign , err := acquired . Campaign ( ctx )
if err != nil {
return nil , err
}
party , err := acquired . Party ( ctx )
if err != nil {
return nil , err
}
catalog , err := acquired . Catalog ( ctx )
if err != nil {
return nil , err
}
base := & config . LoadedPipelineCampaign { Pipeline : pipeline , PipelinePath : acquired . pipelinePath , Campaign : campaign , CampaignPath : acquired . campaignPath , Party : * party , ArtifactCatalog : catalog }
input := sessionInitInput {
Campaign : config . CampaignID ( base . Campaign ) ,
CampaignPath : base . CampaignPath ,
TemplateFile : base . Campaign . SessionTemplateFile ,
SessionID : sessionID ,
PreviousSessionID : previousSessionID ,
Date : date ,
Title : title ,
AudioS3Prefix : audioS3Prefix ,
AudioDir : audioDir ,
}
data , err := buildSessionInitYAML ( input )
if err != nil {
return report , fmt . Errorf ( "session init: %w" , err )
}
label := strings . TrimSpace ( output )
if label == "" {
label = "remote session.yml"
}
// Generated defaults and CLI resources originate at the invocation. A
// configured template supplies its own existing local authoring context.
authoringPath := "session.yml"
if input . TemplateFile != "" {
authoringPath = resolveSessionInitTemplatePath ( input . CampaignPath , input . TemplateFile )
}
sessionCfg , err := config . LoadSessionAuthoringBytes ( authoringPath , data , config . SessionLoadOptions {
Campaign : base . Campaign ,
CampaignPath : base . CampaignPath ,
SessionID : sessionID ,
PreviousSessionID : previousSessionID ,
} )
2026-11-20 05:53:49 +00:00
err = errors . Join ( err , ctx . Err ( ) )
2026-11-20 05:29:27 +00:00
if err != nil {
return report , fmt . Errorf ( "session init: %w" , err )
}
cfg , err := config . ResolveLoadedPipelineCampaign ( * base , label , sessionCfg , config . SessionSource { Source : "session_config" , LocalPath : label } )
if err != nil {
return report , fmt . Errorf ( "session init: %w" , err )
}
if err := config . Validate ( cfg ) ; err != nil {
return report , fmt . Errorf ( "session init: %w" , err )
}
data , err = config . RenderSessionDocument ( cfg , sessionID )
if err != nil {
return report , fmt . Errorf ( "session init: render effective session: %w" , err )
}
2026-11-20 05:53:49 +00:00
if err := ctx . Err ( ) ; err != nil {
return report , err
}
2026-11-20 05:29:27 +00:00
if ! remote {
if err := writeLocalFile ( output , data , force ) ; err != nil {
return report , fmt . Errorf ( "session init: %w" , err )
}
report = & sessionInitializationReport { Campaign : config . CampaignID ( base . Campaign ) , SessionID : sessionID , Destination : filepath . Clean ( output ) , Written : true }
return report , nil
}
store , err := newCommandObjectStoreWithDependencies ( ctx , cfg , nil , deps )
if err != nil {
return report , fmt . Errorf ( "session init: %w" , err )
}
sessionPrefix := artifacts . S3SessionPrefix ( base . Pipeline . Storage . S3 . RootPrefix , config . CampaignID ( base . Campaign ) , sessionID )
key := artifacts . S3SessionConfigKey ( sessionPrefix )
exists , err := store . Exists ( ctx , key )
if err != nil {
return report , fmt . Errorf ( "session init: check remote session %q: %w" , key , err )
}
if exists && ! force {
return report , fmt . Errorf ( "session init: remote session %q already exists; pass --force to overwrite" , key )
}
tmp , err := os . CreateTemp ( "" , "narratio-session-init-*.yml" )
if err != nil {
return report , fmt . Errorf ( "session init: create temp file: %w" , err )
}
tmpPath := tmp . Name ( )
defer func ( ) { err = errors . Join ( err , os . Remove ( tmpPath ) ) } ( )
if _ , err := tmp . Write ( data ) ; err != nil {
return report , fmt . Errorf ( "session init: write temp file: %w" , errors . Join ( err , tmp . Close ( ) ) )
}
if err := tmp . Close ( ) ; err != nil {
return report , fmt . Errorf ( "session init: close temp file: %w" , err )
}
if _ , err := store . Upload ( ctx , tmpPath , key , storage . UploadOptions { ContentType : "application/x-yaml; charset=utf-8" } ) ; err != nil {
return report , fmt . Errorf ( "session init: upload remote session %q: %w" , key , err )
}
report = & sessionInitializationReport { Campaign : config . CampaignID ( base . Campaign ) , SessionID : sessionID , Destination : "s3://" + s3BucketName ( base . Pipeline ) + "/" + key , Remote : true , Written : true }
return report , nil
}