# -*- coding: utf-8 -*-
"""Command-line interface for wordextractor."""

from __future__ import annotations

from pathlib import Path

import click

from wordextractor.config import PipelineConfig


def _load_config(config_path: str | None) -> PipelineConfig:
    if config_path:
        return PipelineConfig.from_yaml(config_path)
    default = Path.cwd() / "config.yaml"
    if default.exists():
        click.echo(f"Auto-discovered config: {default}")
        return PipelineConfig.from_yaml(default)
    return PipelineConfig()


@click.group()
@click.option("--config", "-c", "config_path", default=None, type=click.Path(exists=True), help="Path to config.yaml")
@click.option("--output-dir", "-o", default=None, type=click.Path(), help="Override output directory")
@click.option("--corpus-type", "-t", default=None, help="Override corpus type (e.g. naver_news, youtube)")
@click.pass_context
def main(ctx, config_path, output_dir, corpus_type):
    """Korean Blend Word Extractor — 한국어 혼성어 추출 파이프라인"""
    cfg = _load_config(config_path)
    if output_dir:
        cfg.output_dir = Path(output_dir)
    if corpus_type:
        cfg.corpus_type = corpus_type
    ctx.ensure_object(dict)
    ctx.obj["config"] = cfg


@main.command()
@click.pass_context
def step1(ctx):
    """Extract n-gram patterns from known blend word list."""
    from wordextractor.steps.step1_extract_patterns import run

    run(ctx.obj["config"])


@main.command()
@click.pass_context
def step2(ctx):
    """Build eojeol (word) frequency list from corpus."""
    from wordextractor.steps.step2_build_eojeol_type_freq import run

    run(ctx.obj["config"])


@main.command()
@click.pass_context
def step3(ctx):
    """Pattern matching + filtering + dictionary check."""
    from wordextractor.steps.step3_pattern_matching import run

    run(ctx.obj["config"])


@main.command()
@click.pass_context
def step4(ctx):
    """Search corpus for usage examples."""
    from wordextractor.steps.step4_search_corpus_example import run

    run(ctx.obj["config"])


@main.command()
@click.pass_context
def step5(ctx):
    """LLM-assisted blend word annotation (OpenAI Batch API)."""
    from wordextractor.steps.step5_llm_annotation import run

    run(ctx.obj["config"])


@main.command()
@click.pass_context
def step6(ctx):
    """Search Naver News for first occurrence dates."""
    from wordextractor.steps.step6_naver_first_occurrence import run

    run(ctx.obj["config"])


@main.command(name="run-all")
@click.option("--start", default=1, help="Start from step N (default: 1)")
@click.option("--end", default=6, help="End at step N (default: 6)")
@click.pass_context
def run_all(ctx, start, end):
    """Run steps sequentially (default: all 6 steps)."""
    from wordextractor.steps import STEPS

    cfg = ctx.obj["config"]
    for i in range(start, end + 1):
        step_name = f"step{i}"
        if step_name in STEPS:
            click.echo(f"\n{'=' * 60}")
            click.echo(f"Running {step_name}...")
            click.echo(f"{'=' * 60}")
            STEPS[step_name](cfg)
        else:
            click.echo(f"Unknown step: {step_name}", err=True)


@main.command(name="show-config")
@click.pass_context
def show_config(ctx):
    """Print the resolved configuration."""
    import json
    from dataclasses import asdict

    cfg = ctx.obj["config"]
    d = asdict(cfg)
    click.echo(json.dumps(d, ensure_ascii=False, indent=2, default=str))
