"""Command-line interface for doc-to-skill."""

import os
import click
from pathlib import Path
from dotenv import load_dotenv

from .crawlers import WebCrawler, GitHubCrawler, FirecrawlCrawler, SmartCrawler
from .generators import SkillGenerator, LlmSkillGenerator
from .config import Config

# Load environment variables from .env file
load_dotenv()


@click.group()
@click.version_option()
def main():
    """Doc-to-Skill: Convert documentation to AI-ready skills."""
    pass


@main.command()
@click.argument("url")
@click.option(
    "-o", "--output-dir",
    type=click.Path(path_type=Path),
    default=Path("./docs"),
    help="Output directory for downloaded documentation"
)
@click.option(
    "-d", "--max-depth",
    type=int,
    default=3,
    help="Maximum crawl depth"
)
@click.option(
    "-l", "--limit",
    type=int,
    default=100,
    help="Maximum number of pages to crawl"
)
@click.option(
    "--method", "-m",
    type=click.Choice(["auto", "http", "github", "firecrawl"]),
    default="auto",
    help="Crawling method: auto (smart fallback), http, github, or firecrawl"
)
@click.option(
    "--firecrawl-url",
    default="http://localhost:3002",
    help="Firecrawl API URL (default: http://localhost:3002 for local Docker)"
)
def download(url: str, output_dir: Path, max_depth: int, limit: int, method: str, firecrawl_url: str):
    """Download documentation from URL to local markdown files."""
    firecrawl_key = os.environ.get("FIRECRAWL_API_KEY")
    
    click.echo(f"📥 Downloading documentation from: {url}")
    click.echo(f"   Output directory: {output_dir}")
    click.echo(f"   Method: {method}")
    
    if method == "auto":
        click.echo("   🧠 Smart mode: will try HTTP → GitHub → Firecrawl")
        crawler = SmartCrawler(
            output_dir=output_dir,
            max_depth=max_depth,
            max_pages=limit,
            firecrawl_url=firecrawl_url,
            firecrawl_key=firecrawl_key
        )
    elif method == "http":
        crawler = WebCrawler(
            output_dir=output_dir,
            max_depth=max_depth,
            max_pages=limit
        )
    elif method == "github":
        click.echo("   📦 GitHub mode: downloading from repository")
        crawler = GitHubCrawler(
            output_dir=output_dir,
            max_pages=limit
        )
    elif method == "firecrawl":
        click.echo(f"   🔥 Firecrawl mode: using {firecrawl_url}")
        crawler = FirecrawlCrawler(
            output_dir=output_dir,
            max_depth=max_depth,
            max_pages=limit,
            api_url=firecrawl_url,
            api_key=firecrawl_key
        )
    
    result = crawler.crawl(url)
    
    click.echo(f"✅ Downloaded {result['pages_count']} pages to {output_dir}")
    return result


@main.command()
@click.argument("docs_dir", type=click.Path(exists=True, path_type=Path))
@click.option(
    "-n", "--name",
    required=True,
    help="Name of the service/API for the skill"
)
@click.option(
    "-o", "--output-dir",
    type=click.Path(path_type=Path),
    default=None,
    help="Output directory for generated skill (default: .agent/skills/<name>)"
)
def generate(docs_dir: Path, name: str, output_dir: Path | None):
    """Generate SKILL.md from local documentation directory."""
    if output_dir is None:
        output_dir = Path(".agent/skills") / name.lower().replace(" ", "-")
    
    click.echo(f"🔧 Generating skill '{name}' from: {docs_dir}")
    click.echo(f"   Output: {output_dir}")
    
    generator = SkillGenerator(
        docs_dir=docs_dir,
        skill_name=name,
        output_dir=output_dir
    )
    
    result = generator.generate()
    
    click.echo(f"✅ Generated skill at: {output_dir}")
    click.echo(f"   - SKILL.md: {result['skill_md']}")
    click.echo(f"   - reference.md: {result['reference_md']}")
    return result


def _install_pipeline(url: str, project_path: Path, name: str, max_depth: int, limit: int, method: str, llm: bool = False):
    """Core installation pipeline logic."""
    service_slug = name.lower().replace(" ", "-")
    firecrawl_key = os.environ.get("FIRECRAWL_API_KEY")
    openai_key = os.environ.get("OPENAI_API_KEY")
    
    # Paths
    docs_dir = project_path / "docs" / "api" / service_slug
    skill_dir = project_path / ".agent" / "skills" / service_slug
    
    click.echo(f"🚀 Installing '{name}' documentation as skill")
    click.echo(f"   Source: {url}")
    click.echo(f"   Project: {project_path}")
    click.echo(f"   Method: {method}")
    
    # Step 1: Download
    click.echo("\n📥 Step 1/2: Downloading documentation...")
    
    if method == "auto":
        crawler = SmartCrawler(
            output_dir=docs_dir,
            max_depth=max_depth,
            max_pages=limit,
            firecrawl_key=firecrawl_key
        )
    elif method == "http":
        crawler = WebCrawler(
            output_dir=docs_dir,
            max_depth=max_depth,
            max_pages=limit
        )
    elif method == "github":
        crawler = GitHubCrawler(
            output_dir=docs_dir,
            max_pages=limit
        )
    elif method == "firecrawl":
        crawler = FirecrawlCrawler(
            output_dir=docs_dir,
            max_depth=max_depth,
            max_pages=limit,
            api_key=firecrawl_key
        )
    
    crawl_result = crawler.crawl(url)
    click.echo(f"   Downloaded {crawl_result['pages_count']} pages")
    
    # Step 2: Generate skill
    click.echo("\n🔧 Step 2/2: Generating skill...")
    
    if llm:
        if not openai_key:
            click.echo("⚠️  --llm flag used but OPENAI_API_KEY not found. Falling back to regex parser.")
            generator = SkillGenerator(docs_dir=docs_dir, skill_name=name, output_dir=skill_dir)
        else:
            click.echo("🧠 Using LLM Generator (Smart Mode)...")
            try:
                generator = LlmSkillGenerator(
                    docs_dir=docs_dir, 
                    skill_name=name, 
                    output_dir=skill_dir,
                    api_key=openai_key
                )
            except Exception as e:
                click.echo(f"❌ LLM Error: {e}")
                click.echo("   Falling back to standard generator.")
                generator = SkillGenerator(docs_dir=docs_dir, skill_name=name, output_dir=skill_dir)
    else:
        generator = SkillGenerator(
            docs_dir=docs_dir,
            skill_name=name,
            output_dir=skill_dir
        )
    gen_result = generator.generate()
    
    click.echo(f"\n✅ Installation complete!")
    click.echo(f"   📚 Documentation: {docs_dir}")
    click.echo(f"   🎯 Skill: {skill_dir}")
    click.echo(f"\n💡 Add to your project rules:")
    click.echo(f'   "Use the {name} skill when working with {name} API"')


@main.command()
@click.argument("url")
@click.argument("project_path", type=click.Path(exists=True, path_type=Path))
@click.option(
    "-n", "--name",
    required=True,
    help="Name of the service/API"
)
@click.option(
    "-d", "--max-depth",
    type=int,
    default=3,
    help="Maximum crawl depth"
)
@click.option(
    "-l", "--limit",
    type=int,
    default=100,
    help="Maximum number of pages to crawl"
)
@click.option(
    "--method", "-m",
    type=click.Choice(["auto", "http", "github", "firecrawl"]),
    default="auto",
    help="Crawling method"
)
@click.option(
    "--llm", 
    is_flag=True, 
    help="Use LLM for intelligent generation"
)
def install(url: str, project_path: Path, name: str, max_depth: int, limit: int, method: str, llm: bool):
    """Full pipeline: download docs + generate skill + install to project."""
    _install_pipeline(url, project_path, name, max_depth, limit, method, llm)


@main.command()
def wizard():
    """Interactive wizard for installing skills."""
    click.echo("🧙 Doc-to-Skill Wizard")
    click.echo("=======================")
    
    # 1. URL
    url = click.prompt("🌐 Documentation URL (e.g. https://docs.example.com)")
    
    # 2. Name (try to guess)
    from urllib.parse import urlparse
    parsed = urlparse(url)
    domain = parsed.netloc
    
    default_name = domain.split(".")[0].title()
    
    # Better guessing for GitHub
    if "github.com" in domain:
        parts = parsed.path.strip("/").split("/")
        if len(parts) >= 2:
            default_name = parts[1].title()  # Repo name
            
    if default_name == "Docs":
        try:
            default_name = domain.split(".")[-2].title()
        except:
            pass
    
    name = click.prompt("📦 Name of the service", default=default_name)
    
    # 3. Project Path
    project_path = click.prompt(
        "📂 Project directory", 
        type=click.Path(exists=True, path_type=Path), 
        default=Path(".")
    )
    
    # 4. Method
    method = click.prompt(
        "🕷️  Crawling method",
        type=click.Choice(["auto", "http", "github", "firecrawl"]),
        default="auto"
    )
    
    # 5. Limits (optional, advanced)
    if click.confirm("⚙️  Configure advanced options?", default=False):
        max_depth = click.prompt("   Max depth", type=int, default=3)
        limit = click.prompt("   Page limit", type=int, default=100)
    else:
        max_depth = 3
        limit = 100
    
    # 6. LLM
    llm = click.confirm("🧠 Use Smart LLM Generation?", default=True)
    
    click.echo("\n🚀 Starting installation...")
    _install_pipeline(url, project_path, name, max_depth, limit, method, llm)


@main.command()
def list_skills():
    """List all installed skills in current project."""
    skills_dir = Path(".agent/skills")
    
    if not skills_dir.exists():
        click.echo("No skills found in current project.")
        return
    
    skills = [d for d in skills_dir.iterdir() if d.is_dir() and (d / "SKILL.md").exists()]
    
    if not skills:
        click.echo("No skills found.")
        return
    
    click.echo("📚 Installed skills:\n")
    for skill in skills:
        skill_md = skill / "SKILL.md"
        # Try to extract name from frontmatter
        name = skill.name
        try:
            content = skill_md.read_text(encoding="utf-8")
            for line in content.split("\n"):
                if line.startswith("name:"):
                    name = line.split(":", 1)[1].strip()
                    break
        except:
            pass
        click.echo(f"  • {name} ({skill})")


if __name__ == "__main__":
    main()
