SET ANSI_NULLS ON;
GO
SET QUOTED_IDENTIFIER ON;
GO

IF COL_LENGTH(N'dbo.StoryIntelligenceRuns', N'SourceFileName') IS NULL
    ALTER TABLE dbo.StoryIntelligenceRuns ADD SourceFileName nvarchar(260) NULL;
GO
IF COL_LENGTH(N'dbo.StoryIntelligenceRuns', N'SourceFileSizeBytes') IS NULL
    ALTER TABLE dbo.StoryIntelligenceRuns ADD SourceFileSizeBytes bigint NULL;
GO
IF COL_LENGTH(N'dbo.StoryIntelligenceRuns', N'SourceWordCount') IS NULL
    ALTER TABLE dbo.StoryIntelligenceRuns ADD SourceWordCount int NULL;
GO
IF COL_LENGTH(N'dbo.StoryIntelligenceRuns', N'SourceCharacterCount') IS NULL
    ALTER TABLE dbo.StoryIntelligenceRuns ADD SourceCharacterCount int NULL;
GO
IF COL_LENGTH(N'dbo.StoryIntelligenceRuns', N'SourceChapterCount') IS NULL
    ALTER TABLE dbo.StoryIntelligenceRuns ADD SourceChapterCount int NULL;
GO
IF COL_LENGTH(N'dbo.StoryIntelligenceRuns', N'SourceDetectedImagesCount') IS NULL
    ALTER TABLE dbo.StoryIntelligenceRuns ADD SourceDetectedImagesCount int NULL;
GO
IF COL_LENGTH(N'dbo.StoryIntelligenceRuns', N'SourceDetectedTablesCount') IS NULL
    ALTER TABLE dbo.StoryIntelligenceRuns ADD SourceDetectedTablesCount int NULL;
GO
IF COL_LENGTH(N'dbo.StoryIntelligenceRuns', N'SourceDetectedFootnotesCount') IS NULL
    ALTER TABLE dbo.StoryIntelligenceRuns ADD SourceDetectedFootnotesCount int NULL;
GO
IF COL_LENGTH(N'dbo.StoryIntelligenceRuns', N'SourceDetectedCommentsCount') IS NULL
    ALTER TABLE dbo.StoryIntelligenceRuns ADD SourceDetectedCommentsCount int NULL;
GO
IF COL_LENGTH(N'dbo.StoryIntelligenceRuns', N'FailureStage') IS NULL
    ALTER TABLE dbo.StoryIntelligenceRuns ADD FailureStage nvarchar(80) NULL;
GO
IF COL_LENGTH(N'dbo.StoryIntelligenceRuns', N'ErrorDetail') IS NULL
    ALTER TABLE dbo.StoryIntelligenceRuns ADD ErrorDetail nvarchar(max) NULL;
GO
IF COL_LENGTH(N'dbo.StoryIntelligenceRuns', N'EstimatedCostGBP') IS NULL
    ALTER TABLE dbo.StoryIntelligenceRuns ADD EstimatedCostGBP decimal(19,6) NULL;
GO
IF COL_LENGTH(N'dbo.StoryIntelligenceRuns', N'EstimatedCostUSD') IS NULL
    ALTER TABLE dbo.StoryIntelligenceRuns ADD EstimatedCostUSD decimal(19,6) NULL;
GO
IF COL_LENGTH(N'dbo.StoryIntelligenceRuns', N'PromptVersionsSummary') IS NULL
    ALTER TABLE dbo.StoryIntelligenceRuns ADD PromptVersionsSummary nvarchar(500) NULL;
GO

CREATE OR ALTER PROCEDURE dbo.StoryIntelligenceRun_Save
    @UserID int,
    @ProjectID int = NULL,
    @BookID int = NULL,
    @Status nvarchar(50),
    @SourceType nvarchar(50),
    @SourceFileName nvarchar(260) = NULL,
    @SourceFileSizeBytes bigint = NULL,
    @SourceWordCount int = NULL,
    @SourceCharacterCount int = NULL,
    @SourceChapterCount int = NULL,
    @SourceDetectedImagesCount int = NULL,
    @SourceDetectedTablesCount int = NULL,
    @SourceDetectedFootnotesCount int = NULL,
    @SourceDetectedCommentsCount int = NULL,
    @PromptVersion nvarchar(200),
    @Model nvarchar(100),
    @StartedUtc datetime2,
    @CompletedUtc datetime2 = NULL,
    @FailureStage nvarchar(80) = NULL,
    @TotalInputTokens int = NULL,
    @TotalOutputTokens int = NULL,
    @TotalTokens int = NULL,
    @TotalDurationMs bigint = NULL,
    @EstimatedCostGBP decimal(19,6) = NULL,
    @EstimatedCostUSD decimal(19,6) = NULL,
    @PromptVersionsSummary nvarchar(500) = NULL,
    @ErrorMessage nvarchar(max) = NULL,
    @ErrorDetail nvarchar(max) = NULL
AS
BEGIN
    SET NOCOUNT ON;

    INSERT dbo.StoryIntelligenceRuns
    (
        UserID, ProjectID, BookID, Status, SourceType, SourceFileName, SourceFileSizeBytes,
        SourceWordCount, SourceCharacterCount, SourceChapterCount, SourceDetectedImagesCount,
        SourceDetectedTablesCount, SourceDetectedFootnotesCount, SourceDetectedCommentsCount,
        PromptVersion, Model, StartedUtc, CompletedUtc, FailureStage, TotalInputTokens,
        TotalOutputTokens, TotalTokens, TotalDurationMs, EstimatedCostGBP, EstimatedCostUSD,
        PromptVersionsSummary, ErrorMessage, ErrorDetail
    )
    VALUES
    (
        @UserID, @ProjectID, @BookID, @Status, @SourceType, @SourceFileName, @SourceFileSizeBytes,
        @SourceWordCount, @SourceCharacterCount, @SourceChapterCount, @SourceDetectedImagesCount,
        @SourceDetectedTablesCount, @SourceDetectedFootnotesCount, @SourceDetectedCommentsCount,
        @PromptVersion, @Model, @StartedUtc, @CompletedUtc, @FailureStage, @TotalInputTokens,
        @TotalOutputTokens, @TotalTokens, @TotalDurationMs, @EstimatedCostGBP, @EstimatedCostUSD,
        @PromptVersionsSummary, @ErrorMessage, @ErrorDetail
    );

    SELECT CAST(SCOPE_IDENTITY() AS int) AS StoryIntelligenceRunID;
END;
GO

CREATE OR ALTER PROCEDURE dbo.StoryIntelligenceRun_ListAdmin
AS
BEGIN
    SET NOCOUNT ON;

    SELECT
        r.StoryIntelligenceRunID,
        r.CreatedUtc,
        r.UserID,
        r.ProjectID,
        p.ProjectName AS ProjectTitle,
        r.BookID,
        b.BookTitle,
        r.Status,
        r.SourceType,
        r.FailureStage,
        COUNT(sr.SceneResultID) AS SceneCount,
        r.TotalTokens,
        r.TotalDurationMs,
        r.EstimatedCostGBP,
        r.EstimatedCostUSD,
        COALESCE(cr.ValidationErrorsCount, 0) + COALESCE(SUM(sr.ValidationErrorsCount), 0) AS ValidationErrorsCount,
        COALESCE(cr.ValidationWarningsCount, 0) + COALESCE(SUM(sr.ValidationWarningsCount), 0) AS ValidationWarningsCount
    FROM dbo.StoryIntelligenceRuns r
    LEFT JOIN dbo.Projects p ON p.ProjectID = r.ProjectID
    LEFT JOIN dbo.Books b ON b.BookID = r.BookID
    LEFT JOIN dbo.StoryIntelligenceChapterResults cr ON cr.StoryIntelligenceRunID = r.StoryIntelligenceRunID
    LEFT JOIN dbo.StoryIntelligenceSceneResults sr ON sr.StoryIntelligenceRunID = r.StoryIntelligenceRunID
    GROUP BY
        r.StoryIntelligenceRunID, r.CreatedUtc, r.UserID, r.ProjectID, p.ProjectName,
        r.BookID, b.BookTitle, r.Status, r.SourceType, r.FailureStage, r.TotalTokens,
        r.TotalDurationMs, r.EstimatedCostGBP, r.EstimatedCostUSD,
        cr.ValidationErrorsCount, cr.ValidationWarningsCount
    ORDER BY r.CreatedUtc DESC;
END;
GO

CREATE OR ALTER PROCEDURE dbo.StoryIntelligenceRun_GetAdmin
    @StoryIntelligenceRunID int
AS
BEGIN
    SET NOCOUNT ON;

    SELECT
        r.StoryIntelligenceRunID,
        r.UserID,
        r.ProjectID,
        p.ProjectName AS ProjectTitle,
        r.BookID,
        b.BookTitle,
        r.Status,
        r.SourceType,
        r.SourceFileName,
        r.SourceFileSizeBytes,
        r.SourceWordCount,
        r.SourceCharacterCount,
        r.SourceChapterCount,
        r.SourceDetectedImagesCount,
        r.SourceDetectedTablesCount,
        r.SourceDetectedFootnotesCount,
        r.SourceDetectedCommentsCount,
        r.PromptVersion,
        r.PromptVersionsSummary,
        r.Model,
        r.StartedUtc,
        r.CompletedUtc,
        r.FailureStage,
        r.TotalInputTokens,
        r.TotalOutputTokens,
        r.TotalTokens,
        r.TotalDurationMs,
        r.EstimatedCostGBP,
        r.EstimatedCostUSD,
        r.ErrorMessage,
        r.ErrorDetail,
        r.CreatedUtc,
        r.UpdatedUtc
    FROM dbo.StoryIntelligenceRuns r
    LEFT JOIN dbo.Projects p ON p.ProjectID = r.ProjectID
    LEFT JOIN dbo.Books b ON b.BookID = r.BookID
    WHERE r.StoryIntelligenceRunID = @StoryIntelligenceRunID;
END;
GO
