from __future__ import annotations
import argparse
import hashlib
import json
import re
from dataclasses import dataclass
from pathlib import Path
from typing import Any, Iterable
SOURCE_PATHS = []
DEFAULT_OUTPUT_PATH = Path('chunks.jsonl')
DEFAULT_MAX_CHARS = 2000
MARKDOWN_SUFFIXES = {'.md', '.markdown'}
JSON_SUFFIXES = {'.json'}
SECTION_RE = re.compile('^(##|###)\\s+(.*?)\\s*$', re.MULTILINE)
TOKEN_RE = re.compile('[\\w]+(?:[./-][\\w]+)*', re.UNICODE)
STRONG_FAIL_RE = [re.compile(pattern, re.IGNORECASE) for pattern in ('\\bfalsified\\b', '\\bfailed\\b', '\\bfails\\b', 'rejection upheld', 'honest miss', 'outside-band on both channels')]
FAIL_STATUS_RE = [re.compile(pattern, re.IGNORECASE) for pattern in ('\\bfalsified\\b', '\\bfailed\\b', '\\bfails\\b', '\\bfail\\b', '\\bconcede\\b', '\\bwithdrawn?\\b', '\\bcollapse(?:s|d)?\\b', '\\brejected?\\b', 'honest miss', 'outside-band on both channels')]
PASS_STATUS_RE = [re.compile(pattern, re.IGNORECASE) for pattern in ('\\bsupported\\b', '\\bconfirmed\\b', '\\bobserved\\b', '\\bdefend\\b', '\\bstands\\b', '\\brobust\\b', '\\bintact\\b', '(?m)^\\s*(?:status:\\s*)?\\*{0,2}pass\\b')]
PARTIAL_STATUS_RE = [re.compile(pattern, re.IGNORECASE) for pattern in ('\\bpartial\\b', '\\bpartially\\b', 'with explicit caveats', 'with caveat', '\\bmixed\\b', '\\bnarrowed\\b', '\\bdowngraded\\b', '\\bcontested\\b', '\\bopen\\b')]
PARK_STATUS_RE = [re.compile(pattern, re.IGNORECASE) for pattern in ('\\bpark(?:ed|ing)\\b', '\\bqueue(?:d)?\\b', '\\bdeferred\\b', '\\bpending\\b', '\\bnot run\\b', '\\bin progress\\b', 'work in progress', '\\bstub\\b', '\\bnext steps\\b', '\\bfuture work\\b')]
CONTESTED_LAYER_RE = [re.compile(pattern, re.IGNORECASE) for pattern in ('\\bcontested\\b', '\\bspeculative\\b', 'hostile referee', '\\bmixed\\b', '\\bpartial concede\\b', '\\bconcede largely\\b', '\\battack\\b')]
QUEUE_LAYER_RE = [re.compile(pattern, re.IGNORECASE) for pattern in ('\\bqueue(?:d)?\\b', '\\bdeferred\\b', '\\bpending\\b', '\\bnot run\\b', '\\bin progress\\b', 'work in progress', '\\bnext\\b', '\\brecovery path\\b', '\\bparking lot\\b')]
LAYER2_RE = [re.compile(pattern, re.IGNORECASE) for pattern in ('layer 2', 'visual ground truth', 'token-level visually verified', 'l2_', 're-ocr', 'htr-quality')]

@dataclass(frozen=True)
class Chunk:
    id: str
    text: str
    metadata: dict[str, Any]

    def to_json(self) -> str:
        return json.dumps({'id': self.id, 'text': self.text, 'metadata': self.metadata}, ensure_ascii=False)

def slugify(value: str) -> str:
    slug = re.sub('[^a-z0-9]+', '-', value.lower()).strip('-')
    return slug or 'chunk'

def normalize_space(text: str) -> str:
    lines = [line.rstrip() for line in text.strip().splitlines()]
    return '\n'.join(lines).strip()

def chunk_id_for(citation_target: str) -> str:
    digest = hashlib.sha1(citation_target.encode('utf-8')).hexdigest()[:16]
    return f'substrate-{digest}'

def format_citation_target(path: Path, section: str) -> str:
    return f'{path}::{section}'

def any_match(patterns: Iterable[re.Pattern[str]], text: str) -> bool:
    return any((pattern.search(text) for pattern in patterns))

def infer_status_tags(text: str, source_path: Path, source_section: str) -> list[str]:
    tags: list[str] = []
    scoped_text = f'{source_path.name}\n{source_section}\n{text}'
    if any_match(PASS_STATUS_RE, scoped_text):
        tags.append('pass')
    if any_match(FAIL_STATUS_RE, scoped_text):
        tags.append('fail')
    if any_match(PARK_STATUS_RE, scoped_text):
        tags.append('park')
    if any_match(PARTIAL_STATUS_RE, scoped_text):
        tags.append('partial')
    return tags

def infer_layer_tag(text: str, source_path: Path, source_section: str) -> str:
    source_name = source_path.name.lower()
    scoped_text = f'{source_path.name}\n{source_section}\n{text}'
    section_lower = source_section.lower()
    if any_match(STRONG_FAIL_RE, scoped_text):
        return 'falsified'
    if 'phase_b_adversarial_review' in source_name:
        return 'contested'
    if any_match(CONTESTED_LAYER_RE, scoped_text):
        return 'contested'
    if 'layer2_build_report' in source_name or any_match(LAYER2_RE, scoped_text):
        return '2'
    if 'continuation_plan' in source_name:
        return 'queued'
    if 'next' in section_lower or 'queue' in section_lower or 'parking' in section_lower:
        return 'queued'
    if any_match(QUEUE_LAYER_RE, scoped_text) and (not any_match(PASS_STATUS_RE, scoped_text)):
        return 'queued'
    return '1'

def split_long_section(section_title: str, section_text: str, max_chars: int) -> list[tuple[str, str]]:
    if len(section_text) <= max_chars:
        return [(section_title, section_text)]
    lines = section_text.splitlines()
    heading_line = lines[0] if lines else f'## {section_title}'
    body = '\n'.join(lines[1:]).strip()
    paragraphs = [block.strip() for block in re.split('\\n\\s*\\n', body) if block.strip()]
    parts: list[str] = []
    current = ''
    for paragraph in paragraphs:
        if not current:
            current = paragraph
            continue
        candidate = f'{current}\n\n{paragraph}'
        if len(f'{heading_line}\n\n{candidate}'.strip()) <= max_chars:
            current = candidate
        else:
            parts.extend(split_hard_if_needed(heading_line, current, max_chars))
            current = paragraph
    if current:
        parts.extend(split_hard_if_needed(heading_line, current, max_chars))
    output: list[tuple[str, str]] = []
    for index, body_part in enumerate(parts, start=1):
        title = f'{section_title} [part {index}]'
        text = f'{heading_line}\n\n{body_part}'.strip()
        output.append((title, text))
    return output

def split_hard_if_needed(heading_line: str, body: str, max_chars: int) -> list[str]:
    candidate = f'{heading_line}\n\n{body}'.strip()
    if len(candidate) <= max_chars:
        return [body]
    sentences = re.split('(?<=[.!?])\\s+', body)
    parts: list[str] = []
    current = ''
    for sentence in sentences:
        sentence = sentence.strip()
        if not sentence:
            continue
        if not current:
            current = sentence
            continue
        candidate = f'{current} {sentence}'
        if len(f'{heading_line}\n\n{candidate}'.strip()) <= max_chars:
            current = candidate
        else:
            parts.extend(split_fixed_width(current, max_chars - len(heading_line) - 2))
            current = sentence
    if current:
        parts.extend(split_fixed_width(current, max_chars - len(heading_line) - 2))
    return parts

def split_fixed_width(text: str, width: int) -> list[str]:
    width = max(200, width)
    tokens = TOKEN_RE.findall(text)
    if not tokens:
        return [text[i:i + width].strip() for i in range(0, len(text), width)]
    parts: list[str] = []
    current = ''
    for token in tokens:
        candidate = token if not current else f'{current} {token}'
        if len(candidate) <= width:
            current = candidate
        else:
            if current:
                parts.append(current)
            current = token
    if current:
        parts.append(current)
    return parts

def iter_markdown_sections(path: Path, text: str) -> Iterable[tuple[str, str]]:
    matches = list(SECTION_RE.finditer(text))
    if not matches:
        yield ('Preamble', normalize_space(text))
        return
    preamble = normalize_space(text[:matches[0].start()])
    if preamble:
        yield ('Preamble', preamble)
    for index, match in enumerate(matches):
        start = match.start()
        end = matches[index + 1].start() if index + 1 < len(matches) else len(text)
        block = normalize_space(text[start:end])
        title = match.group(2).strip()
        yield (title, block)

def chunk_markdown(path: Path, max_chars: int) -> list[Chunk]:
    text = path.read_text(encoding='utf-8')
    chunks: list[Chunk] = []
    for section_title, section_text in iter_markdown_sections(path, text):
        if not section_text:
            continue
        for part_title, part_text in split_long_section(section_title, section_text, max_chars):
            citation_target = format_citation_target(path, part_title)
            chunk_id = chunk_id_for(citation_target)
            metadata = {'source_path': str(path), 'source_section': part_title, 'chunk_id': chunk_id, 'layer_tag': infer_layer_tag(part_text, path, part_title), 'substrate_status_tags': infer_status_tags(part_text, path, part_title), 'citation_target': citation_target}
            chunks.append(Chunk(id=chunk_id, text=part_text, metadata=metadata))
    return chunks

def json_text_for_item(key: str, value: Any) -> str:
    rendered = json.dumps(value, ensure_ascii=False, indent=2, sort_keys=True)
    return f'JSON top-level item: {key}\n\n{rendered}'

def iter_json_items(path: Path) -> Iterable[tuple[str, str]]:
    payload = json.loads(path.read_text(encoding='utf-8'))
    if isinstance(payload, dict):
        for key, value in payload.items():
            yield (str(key), json_text_for_item(str(key), value))
        return
    if isinstance(payload, list):
        for index, value in enumerate(payload):
            key = f'[{index}]'
            yield (key, json_text_for_item(key, value))
        return
    yield ('root', json_text_for_item('root', payload))

def chunk_json(path: Path) -> list[Chunk]:
    chunks: list[Chunk] = []
    for section_title, section_text in iter_json_items(path):
        citation_target = format_citation_target(path, section_title)
        chunk_id = chunk_id_for(citation_target)
        metadata = {'source_path': str(path), 'source_section': section_title, 'chunk_id': chunk_id, 'layer_tag': infer_layer_tag(section_text, path, section_title), 'substrate_status_tags': infer_status_tags(section_text, path, section_title), 'citation_target': citation_target}
        chunks.append(Chunk(id=chunk_id, text=section_text, metadata=metadata))
    return chunks

def build_chunks(paths: Iterable[Path] | None=None, max_chars: int=DEFAULT_MAX_CHARS) -> list[Chunk]:
    chunks: list[Chunk] = []
    for path in paths or SOURCE_PATHS:
        if not path.exists():
            raise FileNotFoundError(f'Missing substrate source: {path}')
        suffix = path.suffix.lower()
        if suffix in MARKDOWN_SUFFIXES:
            chunks.extend(chunk_markdown(path, max_chars=max_chars))
        elif suffix in JSON_SUFFIXES:
            chunks.extend(chunk_json(path))
        else:
            raise ValueError(f'Unsupported substrate source type for {path}')
    return chunks

def write_chunks(chunks: Iterable[Chunk], output_path: Path) -> None:
    output_path.parent.mkdir(parents=True, exist_ok=True)
    with output_path.open('w', encoding='utf-8') as handle:
        for chunk in chunks:
            handle.write(chunk.to_json())
            handle.write('\n')

def load_chunks(path: Path=DEFAULT_OUTPUT_PATH) -> list[dict[str, Any]]:
    rows: list[dict[str, Any]] = []
    with path.open(encoding='utf-8') as handle:
        for line in handle:
            line = line.strip()
            if line:
                rows.append(json.loads(line))
    return rows
