// SPDX-License-Identifier: MIT
// Copyright (c) 2025-2026 SenWeaverCoding
// Licensed under the MIT License.

use std::fs;
use std::path::PathBuf;

use anyhow::{Context, Result, bail};
use chrono::Utc;
use tracing::info;

use super::scout::ScoutResult;

pub struct Integrator {
    output_dir: PathBuf,
}

impl Integrator {
    pub fn new(output_dir: String) -> Self {
        Self {
            output_dir: PathBuf::from(output_dir),
        }
    }

    pub fn integrate(&self, candidate: &ScoutResult) -> Result<PathBuf> {
        let safe_name = sanitize_path_component(&candidate.name)?;
        let skill_dir = self.output_dir.join(&safe_name);
        fs::create_dir_all(&skill_dir)
            .with_context(|| format!("Failed to create dir: {}", skill_dir.display()))?;

        let toml_path = skill_dir.join("SKILL.toml");
        let md_path = skill_dir.join("SKILL.md");

        let toml_content = self.generate_toml(candidate);
        let md_content = self.generate_md(candidate);

        fs::write(&toml_path, &toml_content)
            .with_context(|| format!("Failed to write {}", toml_path.display()))?;
        fs::write(&md_path, &md_content)
            .with_context(|| format!("Failed to write {}", md_path.display()))?;

        info!(
            skill = candidate.name.as_str(),
            path = %skill_dir.display(),
            "Integrated skill"
        );

        Ok(skill_dir)
    }

    fn generate_toml(&self, c: &ScoutResult) -> String {
        let lang = c.language.as_deref().unwrap_or("unknown");
        let updated = c
            .updated_at
            .map(|d| d.format("%Y-%m-%d").to_string())
            .unwrap_or_else(|| "unknown".into());

        format!(
            r#"# Auto-generated by SkillForge on {now}

[skill]
name = "{name}"
version = "0.1.0"
description = "{description}"
source = "{url}"
owner = "{owner}"
language = "{lang}"
license = {license}
stars = {stars}
updated_at = "{updated}"

[skill.requirements]
runtime = "sen >= 0.1"

[skill.metadata]
auto_integrated = true
forge_timestamp = "{now}"
"#,
            now = Utc::now().format("%Y-%m-%dT%H:%M:%SZ"),
            name = escape_toml(&c.name),
            description = escape_toml(&c.description),
            url = escape_toml(&c.url),
            owner = escape_toml(&c.owner),
            lang = lang,
            license = if c.has_license { "true" } else { "false" },
            stars = c.stars,
            updated = updated,
        )
    }

    fn generate_md(&self, c: &ScoutResult) -> String {
        let lang = c.language.as_deref().unwrap_or("unknown");
        format!(
            r"# {name}

> Auto-generated by SkillForge

## Overview

- **Source**: [{url}]({url})
- **Owner**: {owner}
- **Language**: {lang}
- **Stars**: {stars}
- **License**: {license}

## Description

{description}

## Usage

```toml
# Add to your SenWeaverCoding config:
[skills.{name}]
enabled = true
```

## Notes

This manifest was auto-generated from repository metadata.
Review before enabling in production.
",
            name = c.name,
            url = c.url,
            owner = c.owner,
            lang = lang,
            stars = c.stars,
            license = if c.has_license { "yes" } else { "unknown" },
            description = c.description,
        )
    }
}

fn escape_toml(s: &str) -> String {
    s.replace('\\', "\\\\")
        .replace('"', "\\\"")
        .replace('\n', "\\n")
        .replace('\r', "\\r")
        .replace('\t', "\\t")
        .replace('\u{08}', "\\b")
        .replace('\u{0C}', "\\f")
}

fn sanitize_path_component(name: &str) -> Result<String> {
    let trimmed = name.trim().trim_matches('.');
    if trimmed.is_empty() {
        bail!("Skill name is empty or only dots after sanitization");
    }
    let sanitized: String = trimmed
        .chars()
        .map(|c| match c {
            '/' | '\\' | '\0' => '_',
            _ => c,
        })
        .collect();
    if sanitized == ".." || sanitized.contains('/') || sanitized.contains('\\') {
        bail!("Skill name '{}' is unsafe as a path component", name);
    }
    Ok(sanitized)
}

