SET ANSI_NULLS ON;
GO
SET QUOTED_IDENTIFIER ON;
GO

CREATE OR ALTER PROCEDURE dbo.StoryIntelligenceImportCommit_GetChapterReadiness
    @ChapterID int
AS
BEGIN
    SET NOCOUNT ON;

    DECLARE @ActiveSceneCount int;
    DECLARE @SceneID int = NULL;
    DECLARE @CanCommit bit = 0;
    DECLARE @HasUntouchedDefaultPlaceholder bit = 0;
    DECLARE @CommitMode nvarchar(80) = N'Blocked';
    DECLARE @BlockReason nvarchar(300) = NULL;

    SELECT @ActiveSceneCount = COUNT(1)
    FROM dbo.Scenes
    WHERE ChapterID = @ChapterID
        AND IsArchived = 0;

    IF @ActiveSceneCount = 0
    BEGIN
        SELECT
            @ActiveSceneCount AS ActiveSceneCount,
            CAST(1 AS bit) AS CanCommit,
            CAST(0 AS bit) AS HasUntouchedDefaultPlaceholder,
            CAST(NULL AS int) AS PlaceholderSceneID,
            CAST(N'EmptyChapter' AS nvarchar(80)) AS CommitMode,
            CAST(NULL AS nvarchar(300)) AS BlockReason;
        RETURN;
    END;

    IF @ActiveSceneCount > 1
    BEGIN
        SELECT
            @ActiveSceneCount AS ActiveSceneCount,
            CAST(0 AS bit) AS CanCommit,
            CAST(0 AS bit) AS HasUntouchedDefaultPlaceholder,
            CAST(NULL AS int) AS PlaceholderSceneID,
            @CommitMode AS CommitMode,
            CAST(N'chapter contains existing authored scenes' AS nvarchar(300)) AS BlockReason;
        RETURN;
    END;

    SELECT TOP (1) @SceneID = SceneID
    FROM dbo.Scenes
    WHERE ChapterID = @ChapterID
        AND IsArchived = 0
    ORDER BY SceneNumber, SceneID;

    IF EXISTS
    (
        SELECT 1
        FROM dbo.Scenes
        WHERE SceneID = @SceneID
            AND SceneNumber = 1
            AND LTRIM(RTRIM(SceneTitle)) IN (N'Scene 1', N'Scene One', N'Untitled Scene', N'Untitled Scene 1')
            AND NULLIF(LTRIM(RTRIM(ISNULL(Summary, N''))), N'') IS NULL
            AND POVCharacterID IS NULL
            AND PrimaryLocationID IS NULL
            AND StartDateTime IS NULL
            AND EndDateTime IS NULL
            AND DurationAmount IS NULL
            AND DurationUnitID IS NULL
            AND NULLIF(LTRIM(RTRIM(ISNULL(RelativeTimeText, N''))), N'') IS NULL
            AND NULLIF(LTRIM(RTRIM(ISNULL(ScenePurposeNotes, N''))), N'') IS NULL
            AND NULLIF(LTRIM(RTRIM(ISNULL(SceneOutcomeNotes, N''))), N'') IS NULL
            AND ISNULL(FloorPlanID, 0) = 0
            AND ISNULL(InitialFloorPlanFloorID, 0) = 0
            AND NULLIF(LTRIM(RTRIM(ISNULL(ImportSource, N''))), N'') IS NULL
            AND ImportRunID IS NULL
            AND SourceStartParagraph IS NULL
            AND SourceEndParagraph IS NULL
    )
    BEGIN
        SET @CanCommit = 1;
    END
    ELSE
    BEGIN
        SELECT TOP (1) @BlockReason =
            CASE
                WHEN SceneNumber <> 1 THEN N'chapter contains existing authored scenes'
                WHEN LTRIM(RTRIM(SceneTitle)) NOT IN (N'Scene 1', N'Scene One', N'Untitled Scene', N'Untitled Scene 1') THEN N'chapter contains existing authored scenes'
                WHEN NULLIF(LTRIM(RTRIM(ISNULL(Summary, N''))), N'') IS NOT NULL THEN N'default scene has summary'
                WHEN POVCharacterID IS NOT NULL THEN N'default scene has POV character'
                WHEN PrimaryLocationID IS NOT NULL THEN N'default scene has location links'
                WHEN StartDateTime IS NOT NULL OR EndDateTime IS NOT NULL OR DurationAmount IS NOT NULL OR DurationUnitID IS NOT NULL OR NULLIF(LTRIM(RTRIM(ISNULL(RelativeTimeText, N''))), N'') IS NOT NULL THEN N'default scene has time data'
                WHEN NULLIF(LTRIM(RTRIM(ISNULL(ScenePurposeNotes, N''))), N'') IS NOT NULL THEN N'default scene has purpose notes'
                WHEN NULLIF(LTRIM(RTRIM(ISNULL(SceneOutcomeNotes, N''))), N'') IS NOT NULL THEN N'default scene has outcome notes'
                WHEN ISNULL(FloorPlanID, 0) <> 0 OR ISNULL(InitialFloorPlanFloorID, 0) <> 0 THEN N'default scene has floor plan links'
                WHEN NULLIF(LTRIM(RTRIM(ISNULL(ImportSource, N''))), N'') IS NOT NULL OR ImportRunID IS NOT NULL OR SourceStartParagraph IS NOT NULL OR SourceEndParagraph IS NOT NULL THEN N'default scene has import source tracking'
                ELSE N'chapter contains existing authored scenes'
            END
        FROM dbo.Scenes
        WHERE SceneID = @SceneID;
    END;

    IF @CanCommit = 1 AND EXISTS (SELECT 1 FROM dbo.SceneNotes WHERE SceneID = @SceneID)
    BEGIN
        SET @CanCommit = 0;
        SET @BlockReason = N'default scene has notes';
    END;

    IF @CanCommit = 1 AND EXISTS (SELECT 1 FROM dbo.SceneMetricValues WHERE SceneID = @SceneID)
    BEGIN
        SET @CanCommit = 0;
        SET @BlockReason = N'default scene has metrics';
    END;

    IF @CanCommit = 1 AND EXISTS (SELECT 1 FROM dbo.ScenePurposes WHERE SceneID = @SceneID)
    BEGIN
        SET @CanCommit = 0;
        SET @BlockReason = N'default scene has purpose records';
    END;

    IF @CanCommit = 1 AND EXISTS (SELECT 1 FROM dbo.SceneOutcomes WHERE SceneID = @SceneID)
    BEGIN
        SET @CanCommit = 0;
        SET @BlockReason = N'default scene has outcome records';
    END;

    IF @CanCommit = 1 AND EXISTS (SELECT 1 FROM dbo.SceneCharacters WHERE SceneID = @SceneID)
    BEGIN
        SET @CanCommit = 0;
        SET @BlockReason = N'default scene has character links';
    END;

    IF @CanCommit = 1 AND EXISTS (SELECT 1 FROM dbo.SceneAssetLocations WHERE SceneID = @SceneID)
    BEGIN
        SET @CanCommit = 0;
        SET @BlockReason = N'default scene has asset links';
    END;

    IF @CanCommit = 1 AND EXISTS (SELECT 1 FROM dbo.SceneFloorPlanOccupancy WHERE SceneID = @SceneID)
    BEGIN
        SET @CanCommit = 0;
        SET @BlockReason = N'default scene has floor plan occupancy';
    END;

    IF @CanCommit = 1 AND EXISTS (SELECT 1 FROM dbo.SceneDependencies WHERE IsArchived = 0 AND (SourceSceneID = @SceneID OR TargetSceneID = @SceneID))
    BEGIN
        SET @CanCommit = 0;
        SET @BlockReason = N'default scene has dependency links';
    END;

    IF @CanCommit = 1 AND EXISTS (SELECT 1 FROM dbo.SceneChecklistItems WHERE SceneID = @SceneID)
    BEGIN
        SET @CanCommit = 0;
        SET @BlockReason = N'default scene has checklist items';
    END;

    IF @CanCommit = 1 AND EXISTS (SELECT 1 FROM dbo.SceneAttachments WHERE SceneID = @SceneID)
    BEGIN
        SET @CanCommit = 0;
        SET @BlockReason = N'default scene has attachments';
    END;

    IF @CanCommit = 1 AND EXISTS (SELECT 1 FROM dbo.ThreadEvents WHERE SceneID = @SceneID)
    BEGIN
        SET @CanCommit = 0;
        SET @BlockReason = N'default scene has thread events';
    END;

    IF @CanCommit = 1 AND EXISTS (SELECT 1 FROM dbo.RelationshipEvents WHERE SceneID = @SceneID)
    BEGIN
        SET @CanCommit = 0;
        SET @BlockReason = N'default scene has relationship events';
    END;

    IF @CanCommit = 1 AND EXISTS (SELECT 1 FROM dbo.AssetEvents WHERE SceneID = @SceneID)
    BEGIN
        SET @CanCommit = 0;
        SET @BlockReason = N'default scene has asset events';
    END;

    IF @CanCommit = 1 AND EXISTS (SELECT 1 FROM dbo.AssetCustodyEvents WHERE SceneID = @SceneID)
    BEGIN
        SET @CanCommit = 0;
        SET @BlockReason = N'default scene has custody events';
    END;

    IF @CanCommit = 1 AND EXISTS (SELECT 1 FROM dbo.CharacterKnowledge WHERE SceneID = @SceneID)
    BEGIN
        SET @CanCommit = 0;
        SET @BlockReason = N'default scene has knowledge records';
    END;

    IF @CanCommit = 1 AND EXISTS (SELECT 1 FROM dbo.CharacterAttributeEvents WHERE SceneID = @SceneID)
    BEGIN
        SET @CanCommit = 0;
        SET @BlockReason = N'default scene has character attribute events';
    END;

    IF @CanCommit = 1 AND EXISTS (SELECT 1 FROM dbo.ContinuityWarnings WHERE SceneID = @SceneID AND IsDismissed = 0)
    BEGIN
        SET @CanCommit = 0;
        SET @BlockReason = N'default scene has continuity warnings';
    END;

    IF @CanCommit = 1 AND EXISTS (SELECT 1 FROM dbo.SceneCharacterSuggestions WHERE SceneID = @SceneID)
    BEGIN
        SET @CanCommit = 0;
        SET @BlockReason = N'default scene has character suggestions';
    END;

    IF @CanCommit = 1 AND EXISTS (SELECT 1 FROM dbo.SceneAssetSuggestions WHERE SceneID = @SceneID)
    BEGIN
        SET @CanCommit = 0;
        SET @BlockReason = N'default scene has asset suggestions';
    END;

    IF @CanCommit = 1 AND EXISTS (SELECT 1 FROM dbo.SceneLocationSuggestions WHERE SceneID = @SceneID)
    BEGIN
        SET @CanCommit = 0;
        SET @BlockReason = N'default scene has location suggestions';
    END;

    IF @CanCommit = 1 AND EXISTS
    (
        SELECT 1
        FROM dbo.SceneWorkflow
        WHERE SceneID = @SceneID
            AND
            (
                DraftStatus <> N'Planned'
                OR EstimatedWordCount IS NOT NULL
                OR ActualWordCount IS NOT NULL
                OR DraftedDate IS NOT NULL
                OR LastWorkedOn IS NOT NULL
                OR ReadyForDraft = 1
                OR ReadyForRevision = 1
                OR ReadyForPolish = 1
                OR IsBlocked = 1
                OR NULLIF(LTRIM(RTRIM(ISNULL(BlockedReason, N''))), N'') IS NOT NULL
                OR Priority IS NOT NULL
            )
    )
    BEGIN
        SET @CanCommit = 0;
        SET @BlockReason = N'default scene has workflow data';
    END;

    IF @CanCommit = 1
    BEGIN
        SET @HasUntouchedDefaultPlaceholder = 1;
        SET @CommitMode = N'ReplaceDefaultPlaceholder';
        SET @BlockReason = NULL;
    END;

    SELECT
        @ActiveSceneCount AS ActiveSceneCount,
        @CanCommit AS CanCommit,
        @HasUntouchedDefaultPlaceholder AS HasUntouchedDefaultPlaceholder,
        CASE WHEN @HasUntouchedDefaultPlaceholder = 1 THEN @SceneID ELSE NULL END AS PlaceholderSceneID,
        @CommitMode AS CommitMode,
        @BlockReason AS BlockReason;
END;
GO
