#!/usr/bin/env python3
from __future__ import annotations
import re, sys, json
from pathlib import Path

SCENE_RE = re.compile(r"^##\s+(?:\d+-\d+|\d+|S\d+)\s+(内景|外景|内外景|INT\.|EXT\.|I/E\.)[·.\s-]+([^·.]+)[·.\s-]+(日|夜|清晨|黄昏|凌晨|连续|稍后|傍晚|上午|下午|深夜|白天|黑夜)(?:\s*)$")
CHAR_RE = re.compile(r"^[A-Za-z0-9\u4e00-\u9fff·]{1,18}(?:（(?:OS|VO|O\.S\.|V\.O\.|重叠|同时|电话|广播|录音)）)?$")
SPECIAL_RE = re.compile(r"^(音效|屏幕文字|字幕|转场|切至|叠化|淡入|淡出)[：:].+")
COMPACT_DIALOGUE_RE = re.compile(r"^[A-Za-z0-9\u4e00-\u9fff·]{1,18}[：:].+")
CAMERA_WORDS = ("特写","俯拍","仰拍","推镜","拉镜","摇镜","跟拍","镜头","焦段","慢放","快切","剪辑点","变焦")

ALLOWED_OUTSIDE = (
    '# ', '---', '```', '>', '- ', '* ', '|', '【', '**', '<!--'
)

def next_nonblank(lines, i):
    j=i+1
    while j < len(lines) and not lines[j].strip(): j+=1
    return lines[j].strip() if j < len(lines) else ''

def validate_text(text:str):
    lines=text.splitlines(); errors=[]; warnings=[]
    in_scene=False; seen_scene=0; state='BASE'; scene_action=0
    for idx, raw in enumerate(lines,1):
        s=raw.strip()
        if not s: continue
        if s.startswith('## '):
            if not SCENE_RE.match(s):
                errors.append(f"L{idx}: invalid scene heading; require scene number + 内/外 + location + time")
            in_scene=True; seen_scene+=1; state='BASE'; scene_action=0; continue
        if s.startswith('# '):
            if in_scene: state='BASE'
            continue
        if not in_scene:
            if s.startswith(ALLOWED_OUTSIDE): continue
            errors.append(f"L{idx}: screenplay content appears before first valid scene heading")
            continue
        if s.startswith('### '):
            errors.append(f"L{idx}: director/shot heading is not allowed in standard screenplay profile")
            continue
        if s == '△' or s.startswith('△△'):
            errors.append(f"L{idx}: empty or duplicated triangle action marker")
            continue
        if s.startswith('△'):
            scene_action+=1; state='BASE'
            action_body=s[1:].strip()
            compact=COMPACT_DIALOGUE_RE.match(action_body)
            # Avoid false positives such as timestamps (22:43), ratios or other action-line numerics.
            if compact and not re.search(r'\d{1,2}:\d{2}', action_body):
                errors.append(f"L{idx}: dialogue cannot be embedded in a triangle action paragraph")
            if any(w in s for w in CAMERA_WORDS):
                warnings.append(f"L{idx}: camera/editing term found in standard screenplay action paragraph")
            continue
        if SPECIAL_RE.match(s):
            state='BASE'; continue
        if s in {'淡出。','淡入。','**全剧终。**','全剧终。'}:
            state='BASE'; continue
        if s.startswith('（') and s.endswith('）'):
            if state not in {'CHAR','PAREN'}:
                errors.append(f"L{idx}: orphan parenthetical; it must follow a character cue")
            state='PAREN'; continue
        if COMPACT_DIALOGUE_RE.match(s):
            errors.append(f"L{idx}: compact 人物：台词 format is not allowed in JINGHUA master scene profile")
            continue
        if CHAR_RE.match(s):
            nxt=next_nonblank(lines, idx-1)
            if not nxt or nxt.startswith(('## ','# ','△')) or SPECIAL_RE.match(nxt):
                errors.append(f"L{idx}: character cue has no dialogue line")
            state='CHAR'; continue
        if state in {'CHAR','PAREN','DIALOGUE'}:
            state='DIALOGUE'; continue
        errors.append(f"L{idx}: unmarked action/environment paragraph; prefix it with △")
    if seen_scene==0: errors.append('no scene headings found')
    return errors,warnings

def main():
    p=Path(sys.argv[1] if len(sys.argv)>1 else 'references/screenplay-format-test-fixture.md')
    e,w=validate_text(p.read_text(encoding='utf-8'))
    print(json.dumps({'status':'PASS' if not e else 'FAIL','errors':e,'warnings':w},ensure_ascii=False,indent=2))
    return 0 if not e else 1

if __name__=='__main__': raise SystemExit(main())
