#!/usr/bin/env python3
import json
import subprocess
import sys
from datetime import datetime, timezone
from pathlib import Path

PROJECT=Path(__file__).resolve().parents[1]
VALIDATOR=PROJECT/'script/validate-story.py'
ORIGINALITY=PROJECT/'script/validate-originality.py'
REPORT=PROJECT/'story/promotion-report.json'
ORIG_REPORT=PROJECT/'story/originality-report.json'
MANIFEST=PROJECT/'script/project-manifest.json'
PLAN=PROJECT/'script/production-plan.json'

def main():
    for validator in (VALIDATOR,ORIGINALITY):
        result=subprocess.run([sys.executable,str(validator)],cwd=PROJECT)
        if result.returncode:return result.returncode
    report=json.loads(REPORT.read_text());orig=json.loads(ORIG_REPORT.read_text());manifest=json.loads(MANIFEST.read_text());plan=json.loads(PLAN.read_text())
    canon=report.get('spoken_sha256')
    if report.get('verified') is not True or orig.get('verified') is not True or orig.get('source_canon_sha256')!=canon: return 1
    if plan.get('outline_sha256')!=manifest.get('outline_hash','').removeprefix('sha256:') or plan.get('reuse_previous_projects') is not False:return 1
    now=datetime.now(timezone.utc).isoformat();plan.update({'status':'story_promoted_ready_for_tts','canon_sha256':canon,'story_words':report['total_words'],'story_estimated_minutes':report['estimated_minutes_at_baseline'],'promoted_at':now})
    manifest.update({'status':'story_promoted','canon_authority':'story/spoken-narration.txt','canon_hash':canon,'story_word_count':report['total_words'],'updated_at':now});manifest['steps']['story']='completed';manifest['steps']['tts']='pending'
    PLAN.write_text(json.dumps(plan,ensure_ascii=False,indent=2)+'\n');MANIFEST.write_text(json.dumps(manifest,ensure_ascii=False,indent=2)+'\n')
    print(json.dumps({'promoted':True,'canon_sha256':canon,'words':report['total_words'],'estimated_minutes':report['estimated_minutes_at_baseline']},ensure_ascii=False));return 0
if __name__=='__main__':sys.exit(main())
