import json
import logging
import re
from typing import Optional, List, Dict, Any

logger = logging.getLogger(__name__)

def clean_json_string(text: str) -> str:
    """ 辅助函数 to strip markdown code blocks from JSON string."""
    text = text.strip()
    if text.startswith("```json"):
        text = text[7:]
    elif text.startswith("```"):
        text = text[3:]
    if text.endswith("```"):
        text = text[:-3]
    return text.strip()

def split_chapters(novel_text: str, regex_pattern: Optional[str] = None) -> List[Dict[str, Any]]:
    # 增强默认正则：
    # 1. 支持 "第x章"、"Chapter x"
    # 2. 支持 "第x节"、"第x回"
    # 3. 允许行首有空白字符
    # 4. 允许 "Chapter" 大小写不敏感 (flags控制)
    default_pattern = r"(^\s*(?:第\s*[0-9一二三四五六七八九十百千万]+\s*[章回节卷集]|Chapter\s*\d+).*$)"
    pattern = regex_pattern if regex_pattern else default_pattern
    
    if not novel_text:
        return []

    try:
        parts = re.split(pattern, novel_text, flags=re.MULTILINE | re.IGNORECASE)
        chapters = []
        
        # Case 1: No split occurred (entire text is one chunk)
        if len(parts) == 1:
            content = parts[0].strip()
            if content:
                chapters.append({"title": "Full Text", "content": content, "word_count": len(content)})
            return chapters
        
        # Case 2: Split successful
        # parts[0] is preamble (text before first chapter title)
        preamble = parts[0].strip()
        if preamble:
            chapters.append({"title": "Introduction", "content": preamble, "word_count": len(preamble)})
        
        # Subsequent parts are [Title, Content, Title, Content...]
        for i in range(1, len(parts), 2):
            title = parts[i].strip()
            # Safety check: ensure content exists
            content = parts[i+1].strip() if i + 1 < len(parts) else ""
            
            if title or content:
                 chapters.append({"title": title, "content": content, "word_count": len(content)})
                 
        return chapters
    except Exception as e:
        # Fallback: return full text as one chapter instead of crashing
        logger.error(f"Regex split failed: {e}")
        return [{"title": "Full Text", "content": novel_text.strip(), "word_count": len(novel_text.strip())}]

def build_context(global_summary: Optional[str] = None, 
                  known_characters: Optional[List] = None,
                  known_scenes: Optional[List] = None,
                  known_props: Optional[List] = None) -> str:
    parts = []
    if global_summary:
        parts.append(f"Global Summary Context:\n{global_summary}")
    
    if known_characters:
        known_chars_str = json.dumps(known_characters, ensure_ascii=False, indent=2)
        parts.append(f"Known Characters (Global Context):\n{known_chars_str}")
        
    if known_scenes:
        known_scenes_str = json.dumps(known_scenes, ensure_ascii=False, indent=2)
        parts.append(f"Known Scenes (Global Context):\n{known_scenes_str}")
        
    if known_props:
        known_props_str = json.dumps(known_props, ensure_ascii=False, indent=2)
        parts.append(f"Known Props (Global Context):\n{known_props_str}")
        
    return "\n\n".join(parts)
